seb-win-refactoring/SafeExamBrowser.Logging/LogFileWriter.cs

54 lines
1.2 KiB
C#
Raw Normal View History

/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* 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;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Logging
{
/// <summary>
/// <see cref="ILogObserver"/> which immediately saves new log content to disk.
/// </summary>
public class LogFileWriter : ILogObserver
{
private readonly object @lock = new object();
private readonly string filePath;
2017-08-07 12:23:56 +02:00
private readonly ILogContentFormatter formatter;
public LogFileWriter(ILogContentFormatter formatter, string filePath)
{
this.filePath = filePath;
2017-08-07 12:23:56 +02:00
this.formatter = formatter;
}
public void Initialize()
{
var directory = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
}
public void Notify(ILogContent content)
{
lock (@lock)
{
2017-08-07 12:23:56 +02:00
var raw = formatter.Format(content);
using (var stream = new StreamWriter(filePath, true, Encoding.UTF8))
{
2017-08-07 12:23:56 +02:00
stream.WriteLine(raw);
}
}
}
}
}