I'm trying to log to a file using NLog based on a globally-set log level. I'm unsure if this is possible from everything I can dig up.
Essentially, I want to have a global setting in my appconfig.json that has the log level. Default would be Debug, but Trace would be another option. If I select Debug, I want to log everything from Debug up to Fatal in a file called log-debug.txt. This seems pretty reasonable; it's the base tutorial case from what I can tell, and I've made that work.
Here's the other thing, though: if I set the global log level to Trace, I want everything from Trace on up to log to log-trace.txt. My initial thought was to add a new config rule, so I added the second one in the rules collection, but from everything I've read that would end up with the debug messages in one file and the trace messages in another.
The purpose of this is extreme-case debugging (i.e., user doesn't have any idea how they got to that state, so flip the setting from "Debug" to "Trace", play with it again, and when you hit the bug send me the log-trace.txt), so splitting the debug and trace messages into different files would defeat the purpose.
How would I go about doing this?
This is a WPF app, so I'm setting the global level by using this in app.xaml.cs:
serviceCollection.AddLogging(builder =>
{
builder.ClearProviders();
// Haven't written the code to pull it from the config file yet, but this is how
// I would set it.
builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
builder.AddNLog();
});
appconfig.json
{
"settings": {
"logLevel": "Debug"
},
"NLog": {
"internalLogLevel": "Info",
"autoReload": true,
"targets": {
"logfile-debug": {
"type": "File",
"fileName": "log-debug.txt",
"layout": "${longdate}|${level}|${message}|${exception:format=tostring}"
},
"logfile-trace": {
"type": "File",
"fileName": "log-trace.txt",
"layout": "${longdate}|${level}|${message}|${exception:format=tostring}",
},
"logconsole": {
"type": "Debugger",
"layout": "${longdate}|${level}|${message}|${exception:format=tostring}"
}
},
"rules": [
{
"logger": "*",
"minLevel": "Debug",
"writeTo": "logfile-debug,logconsole"
},
{
"logger": "*",
"minLevel": "Trace",
"writeTo": "logfile-trace,logconsole"
}
]
}
}
You can do this:
void EnableGlobalTrace(bool enable)
{
NLog.GlobalDiagnosticsContext.Set("GlobalTraceLevel", enable ? "Trace" : "Off");
NLog.LogManager.ReconfigureExistingLoggers();
}
And have the rules like this:
"rules": [
{
"logger": "*",
"minLevel": "Debug",
"writeTo": "logfile-debug,logconsole"
},
{
"logger": "*",
"minLevel": "${gdc:GlobalTraceLevel:whenEmpty=Off}",
"writeTo": "logfile-trace"
}
]
See also: https://github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules
See also: https://github.com/NLog/NLog/wiki/Environment-specific-NLog-Logging-Configuration
Related
Can't take the result of "${configsetting:item=${gdc:item=serviceName}.LogLevel}"
Hi, I created appsettings where I have file target that uses ${gdc:item=serviceName} and writes logs from different services in different files
"type": "File",
"fileName": "${gdc:assemblyFolder}/logs/${gdc:item=serviceName}/${date:format=yyyy-MM-dd}/${gdc:item=serviceLogName}-${date:format=yyyy-MM-dd}.log",
"layout": "${longdate:universalTime=true}|${level:uppercase=true}|${logger}|${scopeproperty:correlationId}|${message:exceptionSeparator=\r\n:withException=true}"
}
{
"logger": "Service1.*",
"minLevel": "${configsetting:item=Service1.LogLevel}",
"ruleName": "Service1",
"writeTo": "fileTarget, consoleTarget"
}
It gets lodlevels from this file
"Service1": {
"LogLevel": "Debug",
"CheckIntervalInMinutes": 1,
...
but my services also uses some packages like TS.Common, so I need to write there logs too. But I can't understand how to use the same log level that service. I tried smth like that:
{
"logger": "TS.*",
"ruleName": "ExecutePackages",
"minLevel": "${configsetting:item=${gdc:item=serviceName}.LogLevel}",
"writeTo": "fileTarget, consoleTarget"
}
but with no effect. Maybe someone knows how to use GDC and configsetting together?
Thanks :)
my code is throwing me expcetion Unhandled exception. NLog.NLogConfigurationException: 'DatabaseParameterInfo' cannot assign unknown property 'parameterName'='#Exception'
I'm using NLog package (5.1.0) in my ASP.NET WEB API project.
My database is PostgreSQL so I use Npgsql (Npgsql.EntityFrameworkCore.PostgreSQL and transitive package Npgsql). My configuration in appsettings.json looks like
...
"NLog": {
"throwConfigExceptions": true,
"autoReload": true,
"extensions": [
{ "assembly": "NLog.Extensions.Logging" },
{ "assembly": "NLog.Web.AspNetCore" }
],
"targets": {
"async": true,
"console": {
"type": "Console"
},
"database": {
"type": "Database",
"dbProvider": "Npgsql.NpgsqlConnection, Npgsql",
"connectionString": "",
"commandText": "INSERT INTO Logs (Exception) VALUES (#Exception)",
"parameters": [
{
"parameterName": "#Exception",
"layout": "${exception:tostring}"
}
]
}
},
"rules": [
{
"logger": "*",
"minLevel": "Trace",
"writeTo": "console"
},
{
"logger": "*",
"minLevel": "Error",
"writeTo": "database"
}
]
},
...
I don't set the connection string in the application settings because I want to do it programmatically in program.cs.
my program.cs looks like
...
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.configuration;
var dbConnectionOptions = new DbConnectionOptions(configuration);
configuration.GetSection("NLog")
.GetSection("targets")
.GetSection("database")
.GetSection("connectionString").Value = dbConnectionOptions.AppDb.ConnectionString;
...
In Npgsql specification https://www.npgsql.org/doc/basic-usage.html#parameters I see, that there are two ways of defining parameters. One is using $ and another is using # but nothing seems to work.
Does anyone know what can I change to fix it?
I've tried setting commandText Values as #Exception, $Exception, Exception, %Exception, and setting parameterName as #Exception, $Exception, Exception, %Exception (mixing all options), but always got same result.
NLog complains about not recognizing the property parameterName.
Try replacing:
"parameterName": "#Exception",
With:
"name": "#Exception",
See also: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json
Also notice that NLog v5 requires NLog.Database-nuget-package for the NLog DatabaseTarget to work.
I am using Serilog in a .Net 5 application, and I am configuring it loading the configuration from appsettings.{env}.json.
In this file I want to specify a different minimum logging level for each sink, and I would like to control it with a LevelSwitch so that I don't need to restart my application only for changing this. To achieve this, I know that restrictedToMinimumLevel can be specified for each sink, but I cannot find an example where it is controlled by a switch. It seems it can only be a string with the logging level, since when I tried to bind it to a switch I got this exception:
System.InvalidOperationException: 'Cannot create instance of type 'Serilog.Events.LogEventLevel' because it is missing a public parameterless constructor.'
Am I missing something? How can I set the minimum logging level for each sink to be easily changed at runtime without restarting my application?
These are my settings:
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"LevelSwitches": {
"$baseSwitch": "Verbose",
"$consoleSwitch": "Warning"
},
"MinimumLevel": {
"ControlledBy": "$baseSwitch"
},
"WriteTo": [
{
"Name": "Console",
"Args": {
//"restrictedToMinimumLevel": "Warning", ---> this works
//"restrictedToMinimumLevel": { ---> this is what I need, but doesn't work
// "ControlledBy": "$consoleSwitch"
//},
"outputTemplate": "{Timestamp} [{Level:u3}] [{LogSource}]: {Message} {Properties}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "Logs/log.txt"
}
}
],
"Enrich": [
"FromLogContext"
]
}
}
I am open also to other solutions. Thank you.
The name of the level switch reference should not have the $ prefix. The $ prefix is only for referencing the level switch declared
{
"Serilog": {
"LevelSwitches": { "consoleSwitch": "Verbose" }, <<<< No $ prefix
"WriteTo": [
{
"Name": "Console",
"Args": {
"levelSwitch": "$consoleSwitch" <<<<<< $ prefix
}
}
]
}
}
Also, the name of the argument for the level switch has to match what's declared in the extension method for the sink. In the case of the Console sink, it's called levelSwitch.
I've setup my sink as follows:
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"pathFormat": "log-{Date}.log",
"fileSizeLimitBytes": 20000000,
}
}
]
My understanding was that once the log-06042019.log file reaches 20000000 bytes, it will start logging to log-06042019-001.log, then to log-06042019-002.log and so on.
But that doesn't happen. It simply stops logging until the next day.
Am I missing something simple in order to enable the rolling characteristics of this sink?
You shouldn't use the RollingFile sink anymore. Instead, use the File Sink.
The file sink has a setting to roll over at a certain size. Here's the C# configuration:
.WriteTo.File("log.txt", rollOnFileSizeLimit: true)
or appsettings.json:
{
"Serilog": {
"WriteTo": [
{ "Name": "File", "Args": { "path": "log.txt", "rollOnFileSizeLimit": "true" } }
]
}
}
I have a .NET Core 2.0 application in which I successfully use Serilog for logging. Now, I would like to log some database performance statistics to a separate sink (they are not for debugging, which basically is the purpose of all other logging in the application, so I would like to keep them separate) and figured this could be accomplished by creating the DB statistics logger with Log.ForContext<MyClass>().
I do not know how I am supposed to configure Serilog using my appsettings.json to log my "debug logs" to one sink and my DB statistics log to another? I am hoping it is possible to do something like:
"Serilog": {
"WriteTo": [
{
"Name": "RollingFile",
"pathFormat": "logs/Log-{Date}.log",
"Filter": {
"ByExcluding": "FromSource(MyClass)"
}
},
{
"Name": "RollingFile",
"pathFormat": "logs/DBStat-{Date}.log",
"Filter": {
"ByIncludingOnly": "FromSource(MyClass)"
}
}
]
}
The "Filter" parts of the configuration is pure guesswork on my part. Is this possible using my configuration filer or do I need to do this in code in my Startup.cs file?
EDIT: I have got it working using the C# API but would still like to figure it out using JSON config:
Log.Logger = new LoggerConfiguration()
.WriteTo.Logger(lc => lc
.Filter.ByExcluding(Matching.FromSource<MyClass>())
.WriteTo.LiterateConsole())
.WriteTo.Logger(lc => lc
.Filter.ByExcluding(Matching.FromSource<MyClass>())
.WriteTo.RollingFile("logs/DebugLog-{Date}.log"))
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(Matching.FromSource<MyClass>())
.WriteTo.RollingFile("logs/DBStats-{Date}.log", outputTemplate: "{Message}{NewLine}"))
.CreateLogger();
I completed this work today, and thought that I'd provide a proper answer since it took me quite a few posts, issues and other pages to work through to get this sorted out.
It's useful to have all the logs, but I also wanted to log only my API code separately, and omit the Microsoft. namespace logs. The JSON config to do that looks like this:
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/var/logs/system.log",
... //other unrelated file config
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/var/logs/api.log",
... //other unrelated file config
}
}
],
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "StartsWith(SourceContext, 'Microsoft.')"
}
}
]
}
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
... //Destructure and other config
}
The top-level WriteTo is the first simple, global, sink. All log events write to this. If you add a Filter section on the same level as this, it will affect all configured WriteTo elements.
Then I configure another WriteTo as a Logger (not File), but the Args for this looks different and has a configureLogger element which serves the same purpose as Serilog on the top level, that is to say, it is the top level of the sub-logger. This means that you can easily split out the config for this into a separate file and add it additionally in the config builder (see bottom).
From here, this sub-logger works the same way: You can configure multiple WriteTos, and the Filter element on this level will affect only this sub-logger.
Simply add more "Name": "Logger" elements to the top level WriteTo section and setup filters for each one separately.
Note
It is also important to note that, even though you are doing all this in config and not referencing a single bit of the Serilog.Filters.Expressions package in your code, you still have to add the NuGet reference to that package. It doesn't work without the package reference.
About splitting the config:
If I have to add more loggers, I would definitely split out the different loggers into separate files for clarity, e.g.
appsettings.json:
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Error",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/var/logs/system.log",
...
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {} // leave this empty
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
...
apilogger.json:
{
"Serilog:WriteTo:1:Args:configureLogger": { //notice this key
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/var/logs/api_separateFile.log",
...
}
}
],
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "StartsWith(SourceContext, 'Microsoft.')"
}
}
]
}
}
And then adjust my IWebHost builder to include the additional config:
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("apilogger.json", optional: false, reloadOnChange: false);
})
.UseStartup<Startup>();
This way it is easier to understand, read and maintain.
I had to do a similar thing, but in code, not JSON. Using a logger as a sink, as described at the bottom of https://github.com/serilog/serilog/wiki/Configuration-Basics did the trick.
In my case I wanted to log everything to a file and to the console, except that messages from a specific source should go only to the file:
private static bool SourceContextEquals(LogEvent logEvent, Type sourceContext)
=> logEvent.Properties.GetValueOrDefault("SourceContext") is ScalarValue sv && sv.Value?.ToString() == sourceContext.FullName;
private static ILogger CreateLogger() =>
new LoggerConfiguration()
.WriteTo.File("mylog.log")
.WriteTo.Logger(lc =>
lc.Filter.ByExcluding(le => SourceContextEquals(le, typeof(TypeThatShouldLogOnlyToFile)))
.WriteTo.Console()
)
.CreateLogger();
Writing only entityframework log to a file is done below but we need to install Serilog.Filters.Expressions nuget package
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"Microsoft.EntityFrameworkCore": "Information"
}
},
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "StartsWith(SourceContext, 'Microsoft.EntityFrameworkCore')"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\LOGS\\TestService_EF_.json",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}
}
}
]
}