I want to log different files with different log templates depending on Users count that are changes only at program start using Serilog.
Let's say we have User object:
class User
{
public string Username { get; set; }
private static ILogger _logger;
public Username()
{
_logger = Log.ForContext("Username", User.Username);
}
public void DoSomething()
{
_logger.Information("I did something!");//Which sends to the {User.Username}-log.txt
//And appends this field to the logtemplate like the example:
//13:25:12 | [INF] | {USERNAME} | I did something!
}
//
}
After creating multiple Users I want to run parallel tasks and log them separate.
private static void Main(string[]? args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Logger(lc => lc.
Filter.ByIncludingOnly(Matching.WithProperty("Username"))
.WriteTo.File("logs/log-{Username}", LogEventLevel.Debug, rollingInterval: RollingInterval.Day)
.WriteTo.Console(LogEventLevel.Debug, "{Timestamp:HH:mm:ss} | [{Level:u3}] | {Username} | {Message}{NewLine}{Exception}", theme: SystemConsoleTheme.Literate))
.WriteTo.Console(LogEventLevel.Debug, "{Timestamp:HH:mm:ss} | [{Level:u3}] | {Message}{NewLine}{Exception}", theme: SystemConsoleTheme.Literate)
.MinimumLevel.Information()
.WriteTo.File("logs/log-", LogEventLevel.Debug, rollingInterval: RollingInterval.Day)
.MinimumLevel.Debug()
.CreateLogger();
var users = new List<User>();
//Init users
foreach (var user in users)
{
Task.Run(() =>
{
while (true)
{
user.DoSomething();
}
});
}
}
I tried to use inside User class but it applies the Username of the last User created.
I came to this way but I don't really like it.
First, configure static logger:
Log.Logger = new LoggerConfiguration()
.WriteTo.Map("Username", "log", (fileName, wt) => wt.File($"logs/{fileName}-.txt", rollingInterval: RollingInterval.Day), restrictedToMinimumLevel: LogEventLevel.Debug)
.CreateLogger();
I used Serilog.Sinks.Map for this, which I use to attach property key trigger "Username" for log files name.
I created my own Logger class for easier property attaching and for the new log template:
internal class Logger
{
public ILogger Log;
public Logger(User user)
{
User = user;
Log = Serilog.Log.ForContext("Username", user.Username);
}
public User User { get; set; }
public void Information(string message)
{
Log.Information(string.IsNullOrEmpty(User.Username) ? message : $"{{Username}} | {message}", User.Username);
}
}
And the usage:
new Logger(User).Information("The most stupid solution but it works honestly.");
Yes, I have to create new Logger() each time I want to log something with a specific user.
Hope someone can show me better way.