2017-07-06 18:18:39 +02:00
|
|
|
|
/*
|
2024-03-05 18:37:42 +01:00
|
|
|
|
* Copyright (c) 2024 ETH Zürich, IT Services
|
2017-07-06 18:18:39 +02:00
|
|
|
|
*
|
|
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Text;
|
2019-08-30 09:55:26 +02:00
|
|
|
|
using SafeExamBrowser.Logging.Contracts;
|
2017-07-06 18:18:39 +02:00
|
|
|
|
|
2018-08-31 10:06:27 +02:00
|
|
|
|
namespace SafeExamBrowser.Logging
|
2017-07-06 18:18:39 +02:00
|
|
|
|
{
|
2018-03-06 14:35:10 +01:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// <see cref="ILogObserver"/> which immediately saves new log content to disk.
|
|
|
|
|
/// </summary>
|
2017-07-06 18:18:39 +02:00
|
|
|
|
public class LogFileWriter : ILogObserver
|
|
|
|
|
{
|
2018-08-31 07:49:41 +02:00
|
|
|
|
private readonly object @lock = new object();
|
2017-07-06 18:18:39 +02:00
|
|
|
|
private readonly string filePath;
|
2017-08-07 12:23:56 +02:00
|
|
|
|
private readonly ILogContentFormatter formatter;
|
2017-07-06 18:18:39 +02:00
|
|
|
|
|
2018-01-17 08:26:44 +01:00
|
|
|
|
public LogFileWriter(ILogContentFormatter formatter, string filePath)
|
2017-07-06 18:18:39 +02:00
|
|
|
|
{
|
2018-01-17 08:26:44 +01:00
|
|
|
|
this.filePath = filePath;
|
2017-08-07 12:23:56 +02:00
|
|
|
|
this.formatter = formatter;
|
2017-07-06 18:18:39 +02:00
|
|
|
|
}
|
|
|
|
|
|
2018-01-17 14:08:39 +01:00
|
|
|
|
public void Initialize()
|
|
|
|
|
{
|
2019-06-18 15:51:35 +02:00
|
|
|
|
var directory = Path.GetDirectoryName(filePath);
|
2018-01-17 14:08:39 +01:00
|
|
|
|
|
2019-06-18 15:51:35 +02:00
|
|
|
|
if (!Directory.Exists(directory))
|
2018-01-17 14:08:39 +01:00
|
|
|
|
{
|
2019-06-18 15:51:35 +02:00
|
|
|
|
Directory.CreateDirectory(directory);
|
2018-01-17 14:08:39 +01:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-07-07 15:46:32 +02:00
|
|
|
|
public void Notify(ILogContent content)
|
2017-07-06 18:18:39 +02:00
|
|
|
|
{
|
|
|
|
|
lock (@lock)
|
|
|
|
|
{
|
2017-08-07 12:23:56 +02:00
|
|
|
|
var raw = formatter.Format(content);
|
|
|
|
|
|
2017-07-06 18:18:39 +02:00
|
|
|
|
using (var stream = new StreamWriter(filePath, true, Encoding.UTF8))
|
|
|
|
|
{
|
2017-08-07 12:23:56 +02:00
|
|
|
|
stream.WriteLine(raw);
|
2017-07-06 18:18:39 +02:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|