Why is Serilog logging in Main() but not in Form1 - serilog

Using Serilog with the MSSQL sink. I am logging OK when I write to the log after defining it in Main(). When I try to write to the log in Form1 form loading event handler it does not log.
The code in Program.cs Main() look like this and works.
var connectionString = #"Data Source=XXX\XXX; Initial Catalog=XXX; User ID=XXX; Password=XXX;";
var sinkOpts = new MSSqlServerSinkOptions();
sinkOpts.TableName = "Logs";
var columnOption = new ColumnOptions();
columnOption.Store.Remove(StandardColumn.MessageTemplate);
Log.Logger = new LoggerConfiguration()
.WriteTo.MSSqlServer(
connectionString: connectionString,
sinkOptions: sinkOpts,
columnOptions: columnOption
).CreateLogger();
Log.Error("nujcsin");
Log.CloseAndFlush();
Code in Form1 loading handler looks like this. It does not log:
private void Form1_Load(object sender, EventArgs e)
{
List<ToolLocationItem> toolList = new List<ToolLocationItem>();
fastObjectListView1.ClearObjects();
fastObjectListView1.Refresh();
FillList();
Log.Information("Testing in Form1");
Log.CloseAndFlush();
}
I have tried replacing "WriteTo" with "AuditTo". I get nothing but my log entry in Main(). My Log.Information is not throwing any errors.
Why is Serilog not logging in Form1?
Edit
Same behaviour when using the file sink. Serilog logs when the logging statement is in the Main procedure but not elsewhere. It seems to be something that Serilog doesn't like rather than the sink.

You have Log.CloseAndFlush() in the code shortly after you initialize your logger. Like the documentation points out, this should be called only once right before the application exits.
Log.CloseAndFlush() will give the sinks a chance to wrap up what they were logging (some sinks are asynchronous) and then kill the logger, so any events logged after that will be lost. It disposes of the logger. So if you call that too soon, you're killing logging in the rest of your app.
You might think that putting it in a variable and then assigning it to the static logger was the solution, but you're misunderstanding what's going on. You haven't shown exactly what you did, but let's say you did this...
var log = new LoggerConfiguration()
.WriteTo.MSSqlServer(
connectionString: connectionString,
sinkOptions: sinkOpts,
columnOptions: columnOption
).CreateLogger();
Log.CloseAndFlush();
Log.Logger = log;
Now you've created a logger, assigned it to a local variable, closed and flushed (destroy/disposed) of the original static logger (there's a default implementation there that does nothing) then assigned the logger from your local variable to be the static logger. The key point is that all of this wouldn't be necessary if you closed and flushed in the proper place in the code, which is right before the program exits.

Wow. A new day and a fresh look.
What I did wrong is the following:
I needed to define the logger like this:
var log = new LoggerConfiguration()
.WriteTo.MSSqlServer(
connectionString: connectionString,
sinkOptions: sinkOpts,
columnOptions: columnOption
).CreateLogger();
and then:
Log.Logger = log;
If I defined my logger like this it did not seem to work outside the Main().
Log.Logger = new LoggerConfiguration()
.WriteTo.MSSqlServer(
connectionString: connectionString,
sinkOptions: sinkOpts,
columnOptions: columnOption
).CreateLogger();

Related

Injected Serilog does log to Debug, but not File

I'm trying to use Serilog with DI in my .NET 6 application. I have Serilog configured like this:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.Debug()
.WriteTo.File(#"D:\log.txt",
retainedFileCountLimit: 5,
rollingInterval: RollingInterval.Day)
.CreateLogger();
and my generic Host using
IHostBuilder host = new HostBuilder().UseSerilog(Log.Logger).Build()
(configuration and service-addidtion not shown here for brevity).
In my service-classes I require an ILogger from the Microsoft.Extensions.Logging Package.
Now, the Problem I have is that I get correct Logging to Debug from everywhere, but the File-Sink only logs when I use Serilogs Log.Debug() Method for example.
If I comment out the "UseSerilog()" on the Hostbuilder I get no logging in Debug also. So Injection of Serilog to ILogger seems to work.
Any Ideas whats happening here ?
So it turns out it was a rather stupid mistake (for anyone interested).
Somehow I thought this was a good Idea:
try {
Log.Debug("Starting Hostbuild");
BuildHost();
}
catch (Exception ex)
{
Log.Fatal(ex, "Hostbuild Failed unexpectedly");
return;
}
finally
{
Log.CloseAndFlush();
}
Which of course reset my Serilog Logger (Log) to default after the Hostbuild was done in BuildHost().
I think I read somewhere that you're supposed to call CloseAndFlush at the end, but then changed where my "end" was...

Serilog ms sql sink not writing to my table

The Log.Information("Hello"); is not writing to the table. I have used the basic configuration here in the readme file and the sink created my table OK on first run. I am certain that my user has read/write permission.
I am expecting the Log.Information("Hello"); to add a row to the table.
Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
var logDB = #"data source=xxxxxx\SQLEXPRESS;initial catalog=Eng;integrated security=False;persist security info=True;user id=xxxx;password=xxxxxxxx";
var sinkOpts = new SinkOptions();
sinkOpts.TableName = "SL24AddInLogging";
sinkOpts.AutoCreateSqlTable = true;
var columnOpts = new ColumnOptions();
columnOpts.Store.Remove(StandardColumn.Properties);
columnOpts.Store.Add(StandardColumn.LogEvent);
columnOpts.LogEvent.DataLength = 2048;
columnOpts.PrimaryKey = columnOpts.TimeStamp;
columnOpts.TimeStamp.NonClusteredIndex = true;
var log = new LoggerConfiguration()
.WriteTo.MSSqlServer(
connectionString: logDB,
sinkOptions: sinkOpts,
columnOptions: columnOpts
).CreateLogger();
I must be doing something wrong. What?
There are a number of things you can do to troubleshoot issues in Serilog. Several are listed in this answer here on StackOverflow:
Serilog MSSQL Sink doesn't write logs to database
I found my issue. In the past when I have used Serilog I have used the static "Log.Information()" rather than my variable that is declared in my code when I create the logger. In this case my declared variable is also "log" - lower case.
Log.Information() - bad.
log.Information() - good.
Edit
In addition, in case you run into this. I have used the static version to have my logging available throughout the entire project. To define a logger and have it available you can use the following pattern:
var log = new LoggerConfiguration()
.WriteTo.MSSqlServer(
connectionString: logDB,
sinkOptions: sinkOpts,
columnOptions: columnOpts
).CreateLogger();
Log.Logger = log;

Serilog, Change the loglevel at runtime for a specific namespace (> MinimumLevel)

This is my default Serilog configuration
SeriLogLevelSwitch.MinimumLevel = LogEventLevel.Information;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(SeriLogLevelSwitch)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
....
How can i change the loglevel to Debug for a specific namespace at runtime when the default is Information?
Each of your MinimumLevel.Override can have its own LoggingLevelSwitch, which allows you to control the log level for each particular override at run-time.
Create individual LoggingLevelSwitch for each override that you intend to modify whilst the app is running, and store these instances in a place that you can access from other parts of your application, which will allow you to change the MinimumLevel of these LoggingLevelSwitch(es).
e.g.
public class LoggingLevelSwitches
{
// Logging level switch that will be used for the "Microsoft" namespace
public static readonly LoggingLevelSwitch MicrosoftLevelSwitch
= new LoggingLevelSwitch(LogEventLevel.Warning);
// Logging level switch that will be used for the "Microsoft.Hosting.Lifetime" namespace
public static readonly LoggingLevelSwitch MicrosoftHostingLifetimeLevelSwitch
= new LoggingLevelSwitch(LogEventLevel.Information);
}
Configure your Serilog logging pipeline to use these LoggingLevelSwitch instances:
static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LoggingLevelSwitches.MicrosoftLevelSwitch)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime",
LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch)
.Enrich.FromLogContext()
.CreateLogger();
// ...
}
Then somewhere in your application, for example, in the code that handles your application configuration that can be changed at run-time, update the LoggingLevelSwitch instance(s) to the new LogEventLevel that you want:
public class AppSettings
{
void ChangeLoggingEventLevel()
{
LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch
.MinimumLevel = LogEventLevel.Error;
LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch
.MinimumLevel = LogEventLevel.Warning;
// ...
}
}
As you can see, the LogEventLevel is controlled by the LoggingLevelSwitch instances, so it's up to you to decide where in your application (and how) these instances will be modified, to affect the logging pipeline.
The example above I'm assuming you have a screen (or API) in your application that a user would be able to configure the logging levels.
If you don't have that, then another approach is to have a background thread that periodically checks a configuration file, an environment variable, or query a database, etc. to determine what these logging levels should be.
If you're using a .NET Core Host, you can use the Options pattern which can handle the refresh of the configuration for you, and allow you to execute code when the configuration changes (where you'd change the MinimumLevel of your LoggingLevelSwitch(es) you have.
You can use an environment variable paired with another MinimumLevel.Override to change the loglevel to Debug for a specific namespace at runtime like so:
using System;
...
SeriLogLevelSwitch.MinimumLevel = LogEventLevel.Information;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(SeriLogLevelSwitch)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.MinimumLevel.Override(Environment.GetEnvironmentVariable("SPECIFIC_NAMESPACE"), LogEventLevel.Debug)
.Enrich.FromLogContext()
....
Then, ensure the environment variable SPECIFIC_NAMESPACE is accessible by your application at runtime. Note that "namespace" is synonymous with "source context prefix"
Environment.GetEnvironmentVariable

How can I create the logger with an enricher in my baseclass that has to use something in the class?

I was using the following in my static constructor of the base class
static ApplicationBase()
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithThreadId()
.Enrich.FromLogContext()
.MinimumLevel.Debug()
.WriteTo.Async(a => a.RollingFile(
new RenderedCompactJsonFormatter(),
#"c:\logs\log-{Date}.txt", fileSizeLimitBytes: 4194304))
.CreateLogger();
}
Now I need to attach one of our own custom enricher. The enricher is expecting a function that must use a modifier of the actual Application class.
For example, I need to do
.Enrich.WithStoreData(()=>GetStoreData)
Well, it doesn't have to be a function, the bottom line is, the call of GetStoreData is using an object instantiated in the actual child application class (and I cannot change the lifecycle of that object), so I can't access the object from the static constructor.
That means I have to move the logger creation to the normal base constructor. Because it has many children, how can I ensure the logger creation is executed only once? That means I have to apply a lock and check if the logger has been created already. That's really ugly.
And I am not using any container like autofac, so I will not want to create a wrapper of the logger.
At this point, I can only think of the idea creating the logger in the base constructor, and protect it with a lock.
Any other suggestion?
You can only use enrichment while configuring Serilog, and if you are configuring your static logger in your base class, then you cannot change the enrichment later at run time.
But you can use Contextual loggers at run time to add additional properties to your logger: Serilog Context and Correlation
Adding Log Context
// Log.Logger is initialized in your static base
var StudentLogger = Log.Logger.ForContext<Student>();
StudentLogger.Error(/* log message */);
Adding correlation:
// Log.Logger is initialized in your static base
var orderId = "some value";
var corrLog = Log.Logger.ForContext("orderId", orderId)
corrLog.Error(/* log message */);

Serilog separate rolling files for each SourceContext

this is my serilog configuration :
Log.Logger = new LoggerConfiguration()
.WriteTo.RollingFile(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
#"Logs\log-{Date}.txt"))
.MinimumLevel.ControlledBy(LogLevelSwitch)
.CreateLogger();
i'm logging like this :
var log = Serilog.Log.ForContext<SomeClassName>();
log.Information("some log text");
My question :
I need a modification in my configuration to create separate logs for each SourceContext.
I need log files somthing like Logs\log-{Date}-{SourceContext}.txt
thanks pros...
One way to implement this is to create your own ILogEventSink implementation (the interface is very simple) that internally dispatches to one of several RollingFileSinks based on the SourceContext property of the LogEvent.
To configure it (let's say you call your sink SourceRollingFileSink) you can use WriteTo.Sink():
Log.Logger = new LoggerConfiguration()
.WriteTo.Sink(new SourceRollingFileSink())
.CreateLogger();
There's no out-of-the-box implementation so some work is required, but it should not be complicated. Be aware that implementations of ILogEventSink need to be thread-safe.

Resources