-
Notifications
You must be signed in to change notification settings - Fork 82
Open
Description
Hello!
I'm trying to use MetroLog (version 1.0.1) in a simple console app.
I implemented class MyTarget and inherited it from the BufferedTarget.
The main idea is to write logs to the file in large portions (and do it asynchronously).
using MetroLog;
using MetroLog.Layouts;
using MetroLog.Targets;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace LogTest
{
class MyTarget : BufferedTarget
{
public MyTarget(int threshold) : base(new SingleLineLayout(), threshold) { }
protected override async Task DoFlushAsync(LogWriteContext context, IEnumerable<LogEventInfo> toFlush)
{
var logInformation = toFlush.ToList().Aggregate(string.Empty,
(current, eventInfo) => $"{current}{eventInfo.SequenceID}|{eventInfo.TimeStamp}|{eventInfo.Level}|{eventInfo.Logger}|{eventInfo.Message} {eventInfo.ExceptionWrapper?.AsString}{Environment.NewLine}");
using (StreamWriter sourceStream = File.CreateText("newfile.txt")) // TODO pass fileName
{
await sourceStream.WriteAsync(logInformation);
};
}
}
}
And test app:
using MetroLog;
using System;
namespace LogTest
{
class Program
{
private const int COUNT = 1000;
private const int THRESHOLD = COUNT + 1; // decrease this value to get log file in app folder
private static readonly ILogger Logger;
static Program()
{
var config = new LoggingConfiguration();
config.AddTarget(LogLevel.Trace, LogLevel.Fatal, new MyTarget(THRESHOLD));
Logger = LogManagerFactory.CreateLogManager(config).GetLogger("MyTestLog");
}
static void Main(string[] args)
{
Console.WriteLine("Testing MyTarget");
for (uint i = 1; i <= COUNT; ++i)
{
Logger.Info($"counter = {i}");
}
Console.WriteLine("Test is done. Press any key and then check app folder");
Console.ReadKey();
}
}
}
If the number of log entries is greater than the threshold, they will be written to the file.
But if we reduce the number of log entries (COUNT) or increase the threshold, the file will not be written.
Thus logs will be lost.
Is there any way to flush the logs before exiting the application?
Metadata
Metadata
Assignees
Labels
No labels