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

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 */);

Related

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

StructureMap and Proto.Actor in .NET Core 2

I have been using Proto.Actor and specifically the ActorFactory to spawn actors. To be able to use these features I need to add services.AddProtoActor() to the ConfigureServices method of my startup class.
However, now I want to transition to using StructureMap as my IoC container, but the two do not appear to play nicely together - when I add the following code from guides I have found online:
public IServiceProvider ConfigureIoC(IServiceCollection services)
{
// static class method that scans assemblies
IContainer container = IocContainer.SetupContainer();
container.Configure(config =>
{
config.Populate(services);
});
return container.GetInstance<IServiceProvider>();
}
When it tries to run config.Populate I get the following error:
System.ArgumentOutOfRangeException: Specified argument was out of the
range of valid values. Parameter name: EventStream must have at
least one public constructor to be plugged in by StructureMap
Does anyone have any ideas how to get the IActorFactory created correctly as a singleton in StructureMap (or have a workaround)?
In the end, using StructureMap removes the need I had for the ActorFactory itself. So instead of getting the actor's PID from the factory I have two lines:
var props = Actor.FromProducer(() => container.GetInstance<MyActorType>());
var pid = Actor.Spawn(props);

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.

How can I configure a new IDataBus implementation which has a dependency which needs to be injected in NServiceBus?

I want to replace the default IDataBus implementation (which writes to the filesystem) with one which writes to a db (so it can run on AWS). To this end I have a config extension:
public static class ConfigureSqlServerDataBus
{
public static Configure SqlServerDataBus(this Configure config)
{
var dataBus = new SqlServerDataBus();
config.Configurer.RegisterSingleton<IDataBus>(dataBus);
return config;
}
}
to allow me to configure the bus. But obviously my SqlServerDataBus has a dependency on something which tells it where to write (An IRepository implementation in this case).
Usually I would ask for the dependency through the constructor, but as the config of the service bus is done through the IWantCustomInitialization which will use Activator to create the instance I can't. My understanding is that NServiceBus will use property injection to satisfy the dependencies but it doesn't seem to do this. I have a couple of calls like this after my configuration is done:
Configure
.With()
.DefineEndpointName("SomeName")
.DefaultBuilder()
.DBSubcriptionStorage()
.XmlSerializer()
.SqlServerDataBus()
.MsmqTransport()
.IsTransactional(true)
.UnicastBus()
.LoadMessageHandlers()
.CreateBus()
.Start(() => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install());
Configure.Instance.Configurer.ConfigureComponent<RepositoryImplementation>(ComponentCallModelEnum.None);
Configure.Instance.Configurer.ConfigureComponent<SqlServerDataBus>(ComponentCallModelEnum.None);
but my setters for the SqlServerDataBus are never called, although the Put method is.
Can someone point out what I'm doing wrong?
You can't change the configuration after the bus has already been started. To move your config calls into the fluent initialization code, use the RunCustomAction method.
Alternatively, you can write a new class which implements INeedInitialization and make your config calls in there. This class will be invoked at the right time.

My logging framework is tied to my application forever!

Ok, so I'm looking at NLog. Based on the usage, my application would be tied to the logging framework. How do I overcome this?
Also, when using NLog, I have to write too much monkey-code for every class I'm using this framework on. Is it a good practice to make one static class and access it from anywhere in my application?
example:
//the monkey code
private static Logger logger = LogManager.GetCurrentClassLogger();
//the coupling.
logger.Log(/*...*/);
Create your own logging interface:
public interface IMyOwnLogger {
void Log(string message);
}
Create implementation:
public class NLogLogger : IMyOwnLogger {
void Log(string message) {
StackFrame frame = new StackFrame(1, false);
Logger logger = LogManager.GetLogger(frame.GetMethod().DeclaringType.FullName);
logger.Log(/*...*/);
}
}
Bind IMyOwnLogger to NLogLogger in your IOC container.
Inject where needed (or use IOC.Get<IMyOwnLogger>()).
EDIT:
Idsa made a comment about loosing calling class. Remember you can always use stack trace:
var method = (new StackTrace()).GetFrame(1).GetMethod()
and extract calling class from there.
EDIT:
This is how GetCurrentClassLogger in NLog looks like, so using StackTrace in our class doesn't create additional overhead:
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(1);
#else
StackFrame frame = new StackFrame(1, false);
#endif
return globalFactory.GetLogger(frame.GetMethod().DeclaringType.FullName);
}
Personally, I avoid tying any logging framework to my code by using
TraceSource to instrument my code. I then use a logging framework (typically Enterprise Library's Logging Application Block) to "listen" to trace output at runtime and do whatever is necessary with that information. (i.e. write to a database, send emails, etc)

Resources