I am trying to write log into "LocalApplicationData" using Serilog and using below configuration, but it's not working. If I try to write in some hard code path like "path": "C:/Temp/Logs/log.txt" then this is working. How to write into local app data folder?
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "${specialfolder:folder=LocalApplicationData}/Logs/log.txt",
"fileSizeLimitBytes": "5242880",
"rollingInterval": "Day",
"retainedFileCountLimit": "15",
This format is used in NLog. The equivalent is to use %LOCALAPPDATA% instead:
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "%LOCALAPPDATA%/Logs/log.txt",
"fileSizeLimitBytes": "5242880",
"rollingInterval": "Day",
"retainedFileCountLimit": "15",
Please note that this will only work in appSettings.json. To do the equivalent in C# you can use Environment.GetEnvironmentVariable("LocalAppData")
Related
I would like to be able to use the console for user command inputs (ex: console.Readkey()). The problem is that a colleague incorporated serilog as our logging method and uses the console as a sink which seems to ignore every Console.Write() or Console.ReadLine() instruction in my C# code.
Is there a way around this without having to create a 2nd console instance?
EDIT: here is the extract of the serilog config in my json configuration file
"Logging": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File",
"Serilog.Sinks.Debug"
],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "Console",
"Args": {
"restrictedToMinimumLevel": "Debug",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "xxxxxxxx.log",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
"retainedFileCountLimit": 10,
"fileSizeLimitBytes": 10240000,
"restrictedToMinimumLevel": "Debug",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "Debug",
"Args": {
"restrictedToMinimumLevel": "Debug",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
You could remove the configuration log for the Console and keep just the File and Debug. Remove it from Using and WriteTo arrays:
"Logging": {
"Using": [
"Serilog.Sinks.File",
"Serilog.Sinks.Debug"
],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "xxxxxxxx.log",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
"retainedFileCountLimit": 10,
"fileSizeLimitBytes": 10240000,
"restrictedToMinimumLevel": "Debug",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "Debug",
"Args": {
"restrictedToMinimumLevel": "Debug",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
]
}
I am not sure but maybe the Debug log on Console as well (or on the output window on visual studio). If it is disturbing on the console remove it as suggested on the Console.
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'm using Serilog on a .net core.
I want to config the log path to the application directory.
I see there's an extension https://github.com/serilog/serilog-settings-configuration that enable Serilog to read from Configuration.
In the example , the path is configured as "%TEMP%\\Logs\\serilog-configuration-sample.txt".
How can I set it to the working directory?
I've searched on so, and know that it can be done by code, but it seems there's no one asking how to do this by the config file, i.e. appsettings.json.
Current configuration:
{
"Serilog": {
"Using": [
"Serilog.Sinks.File"
],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File",
"Args": { "path": "Logs\\serilog-configuration-sample.txt" }
}
],
"Enrich": [ "FromLogContext", "WithMachineName" ],
"Destructure": [
],
"Properties": {
}
},
"AllowedHosts": "*"
}
I want the log path to be set to the working directory.
But currently it's in "C:\Program Files\IIS Express".
Configuring path like Logs/log.txt will write log files under logs folder in working directory
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log.txt"
}
}
Also you can check this answer for another option
You can add a "RollingFile" wich can write to a local path file. In this example I'm writing in a File inside of the root of my project as it shows bellow.
{
"Name": "RollingFile",
"Args": {
"pathFormat": ".\\Logs\\logs.txt",
"fileSizeLimitBytes": 1048576
}
},
Also the full json on appsettings.json end up like this (in case you need a full example)
...
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"System": "Debug",
"Microsoft": "Debug"
}
},
"WriteTo": [
{
"Name": "ApplicationInsightsEvents",
"Args": {
"instrumentationKey": "xxxxxxxxxx"
}
},
{
"Name": "RollingFile",
"Args": {
"pathFormat": ".\\Logs\\logs.txt",
"fileSizeLimitBytes": 1048576
}
},
{ "Name": "Console" },
{
"Name": "EventLog",
"Args": {
"source": "API NAME",
"logName": "CustomLog",
"restrictedToMinimumLevel": "Warning"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "API NAME"
}
}
...
Is there a way to differentiate what level is logged between the different loggers for Serilog? I want to be able to log MinimumLevel Debug to the console output but only Warning and above to my file output. I am using ASP.NET Core 2.1 and this is what the appsetting.json currently looks like:
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "RollingFile",
"IsJson": true,
"Args": {
"pathFormat": "C:\\Logs\\Log-{Hour}.json",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
},
{
"Name": "Console"
}
]
},
Is it something like another parameter under "Args"? I've tried "minimumnLevel" in this location but it did not work.
The setting you're looking for is restrictedToMinimumLevel. This GitHub issue shows some examples of this, but for your example, you just need to add restrictedToMinimumLevel to your Args for RollingFile:
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "RollingFile",
"IsJson": true,
"Args": {
"pathFormat": "C:\\Logs\\Log-{Hour}.json",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
"restrictedToMinimumLevel": "Warning"
}
},
{
"Name": "Console"
}
]
},
Working from the answers above, this is how I set it up in code as opposed to config
LoggerConfiguration GetConfig()
=> new LoggerConfiguration()
.WriteTo.Seq(serverUrl: "http://localhost:5341", restrictedToMinimumLevel: LogEventLevel.Debug)
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Error);
var logger = GetConfig().CreateLogger();
builder.RegisterInstance(logger).As<ILogger>();
After I did this, it worked for log level Information and above. Debug didn't work. This post explained why.
I had to set a 'global' minimum level like this.
LoggerConfiguration GetConfig()
=> new LoggerConfiguration()
.WriteTo.Seq(serverUrl: "http://localhost:5341", restrictedToMinimumLevel: LogEventLevel.Debug)
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Error)
.MinimumLevel.Verbose();
In your configuration you have one Serilog logger, but you have 2 sinks. One of your sinks is RollingFile and the other is Console.
You can override (but only raise) the minimum logging level per sink, The argument is called restrictedToMinimumLevel.
Since you want to raise the minimum logging level from your logger's default Debug to Warning in your file sink, in your appsettings.json file, it would look like this:
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "RollingFile",
"IsJson": true,
"Args": {
"pathFormat": "C:\\Logs\\Log-{Hour}.json",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
"restrictedToMinimumLevel": "Warning"
}
},
{
"Name": "Console"
}
]
},
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
}
}
]
}
}
}
]
}