I use Serilog on the server side for all my .NETCore services using console, file and Graylog sinks. I also like to use it in my Windows fat clients (WPF applications).
With the latter I have a problem since I do not see, how I can add another file sink AFTER a user successfully logged in. I need an application log stored in the global AppData (Environment.SpecialFolder.CommonApplicationData)
folder and another User-log in a user subfolder e.g. something like this:
var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
AppDataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), appName);
Directory.CreateDirectory(AppDataDir);
AppLogDir = Path.Combine(AppDataDir, $@"Logs");
Directory.CreateDirectory(AppLogDir);
Log.Logger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.Enrich.WithExceptionDetails()
.Enrich.FromLogContext()
.Enrich.WithProcessName()
.Enrich.WithThreadId()
.Enrich.WithAssemblyName()
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] " +
"ThreadId: [{ThreadId}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(Path.Combine(AppLogDir, $"{appName}-.log"), rollOnFileSizeLimit: true,
fileSizeLimitBytes: 1048576, retainedFileCountLimit: 30,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] " +
"[ThreadId: {ThreadId}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
Then in my LoginViewModel
after a successful login and long after the initial application logger was configured, I know the username and can create a folder for that user and put a logfile there:
var userLogDir = Path.Combine(AppDataDir, userName); // <-- userName comes from login token
Directory.CreateDirectory(userLogDir);
And now comes the tricky bit: How can I add a file sink to my existing logger configuration??? I need something like:
var loggerConfig = Log.GetLoggerConfiguration(); //<--- This is missing, at least I could not find it!
loggerConfig.WriteTo.File(Path.Combine(userLogDir, $"{appName}-{userName}-.log"), rollOnFileSizeLimit: true,
fileSizeLimitBytes: 10485760, retainedFileCountLimit: 30,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] " +
"[ThreadId: {ThreadId}] {Message:lj}{NewLine}{Exception}")
Any idea how this can be accomplished with Serilog?