48

I am trying to use WriteTo.RollingFile with Serilog as the following to write one file per day:

var log = new LoggerConfiguration().WriteTo.RollingFile(
                    @"F:\logs\log-{Date}.txt",
                    LogEventLevel.Debug).CreateLogger();
            log.Information("this is a log test");

But I am getting a new log file for each log entry during the same day!

How does one configure Serilog to write to a new file every day as to have a have a single log file per day?


And is there any archiving process to delete files older than 7 days?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
TechNerd
  • 910
  • 1
  • 10
  • 19

9 Answers9

66

Try below:

 var log = new LoggerConfiguration()
          .MinimumLevel.Debug()
          .WriteTo.File(@"f:\log\log.txt", rollingInterval: RollingInterval.Day) 
          .CreateLogger();

The log file name will be automatically log-20150819.txt etc. You do not need to specify the date.Old files will be cleaned up as per retainedFileCountLimit - default is 31.

Infinity Challenger
  • 1,090
  • 10
  • 19
  • 4
    This solves one of his questions. The other is a question that I also had about multiple log files being created in the same day. But one of the comments nailed it on the head. Configure only once and use the same log instances for all messages. I have configured once but I'm trying to figure out how to use it throughout the application. If I don't configure in each class then logging stops. It's due to my in-experience. – Daniel Jackson Oct 12 '17 at 17:23
  • 1
    WriteTo.RollingFile is now Deprecated read the Github page: https://github.com/serilog/serilog-sinks-rollingfile – Enkode Oct 05 '20 at 23:15
  • Rather use Log.Logger = new LoggerConfiguration()........ This way you have a global handle and you use it like this: Log.Information("Hello"); or Log.Error("This is an error"); – Yster Jul 28 '21 at 09:34
  • "rollOnFileSizeLimit": true helped me – TheNerdyNerd Jun 07 '22 at 13:51
34

WriteTo.RollingFile Deprecated

Since the posted answer, the method RollingFile is no longer viable and replaced with File and options to roll the logs.

Now one must use the standard Serilog.Sinks.File NuGet package which supports rolling:

.WriteTo.File(path: @"e:\logs\skilliam.log", 
              rollingInterval: RollingInterval.Day,
              rollOnFileSizeLimit: true, 
              fileSizeLimitBytes: 123456);
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Mohammed Noureldin
  • 14,913
  • 17
  • 70
  • 99
  • It's in `Serilog.Sinks.RollingFile` now (without `rollingInterval: RollingInterval.Day` it seems). – Yahoo Serious Jul 05 '19 at 15:17
  • @YahooSerious, but how do you define the period of rolling? – Mohammed Noureldin Jul 05 '19 at 15:19
  • According to https://github.com/serilog/serilog-sinks-rollingfile, you use `{Date}`, `{Hour}` or `{HalfHour}`. But they also state it's deprecated. So I tried your code again, and it works now. I wonder why it did not work for me the first time. Maybe another package/version, or maybe I tried `RollingFile` instead of `File`? Well, I guess that's "water under the bridge". – Yahoo Serious Jul 09 '19 at 08:49
6

Here is a way to use Serilog with a web.config in an asp.net MVC 4/5 app.

In your web.config add the following:

<add key="serilog:minimum-level" value="Information" />
<add key="serilog:minimum-level:override:Microsoft" value="Information" />
<add key="serilog:minimum-level:override:System" value="Information" />
<add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" />
<add key="serilog:write-to:RollingFile.pathFormat" value="./Logs/log-{Date}.txt" />
<add key="serilog:write-to:RollingFile.outputTemplate" value="{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] {Message}{NewLine}{Exception}" />
<add key="serilog:write-to:RollingFile.retainedFileCountLimit" value="10" />

Then in Application_Start of global.asax add the following:

// Get application base directory
string basedir = AppDomain.CurrentDomain.BaseDirectory;

// Setup Serilog for logging
Log.Logger = new LoggerConfiguration()
            .ReadFrom.AppSettings()
            .WriteTo.RollingFile(basedir + "/Logs/log-{Date}.txt")
            .CreateLogger();
codecypher
  • 837
  • 9
  • 14
6

To enable multi-process shared log files, set shared to true:

in code

.WriteTo.RollingFile("log-{Date}.txt", shared: true)

or in web.config

<add key="serilog:write-to:RollingFile.shared" value="true" />
Stefan Varga
  • 479
  • 6
  • 6
  • how can i set shared property via appsetting.json, can you pls giv a sample.. I tried this, but it doesnt work.. "Name": "RollingFile", "Args": { "pathFormat": "D:\\Log-{Date}.json", "shared": "true" – user1066231 Jun 22 '20 at 22:56
  • https://stackoverflow.com/questions/40880261/configuring-serilog-rollingfile-with-appsettings-json – John Aug 15 '21 at 13:04
  • multi-process shared log files for Blazor app (web) ? – Kiquenet Oct 11 '22 at 08:23
5

To use the same file, you have to add shared: true

.WriteTo.RollingFile("log-{Date}.txt", shared: true)

Diego
  • 2,238
  • 4
  • 31
  • 68
2

As a follow up to this make sure you then use the globally scoped "Log" instance.

Example:

Log.Information("Hello world");
Matt
  • 425
  • 3
  • 13
2

WriteTo.RollingFile Deprecated -> With Formatter

If one is using a text formatter ITextFormatter, note that the variable positions of the path has switched to be second place when using File.

So use this format with a formatter:

var filepath = @"C:\Logs";
ITextFormatter jsonFormatter = new Serilog.Formatting.Json.JsonFormatter(renderMessage: true);

...

Log.Logger = new LoggerConfiguration()
                  ... // Enrichers etc...
                 .WriteTo.File(formatter: jsonFormatter,
                               path: filepath,                            
                               rollingInterval: RollingInterval.Day,
                               rollOnFileSizeLimit: true, 
                               fileSizeLimitBytes: 123456,
                               shared: true)
                 .CreateLogger();
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
1

First of all. You need to add these nugets:

        <PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
        <PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
        <PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" />
        <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
        <PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
        <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />

Than set your serilog in appsettings.json:

 "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File"
    ],
    "MinimumLevel": {
      "Default": "Information"
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "Path": "../Logs/MyLog-.json",
          "RollingInterval": "Day",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
        }
      },
      {
        "Name": "File",
        "Args": {
          "Path": "../Logs/MyLog-.log",
          "RollingInterval": "Day",
          "OutputTemplate": "[({Component}|{MachineName}|{ThreadId}) {Timestamp:G} [{Level:u3}]{Message:lj}{NewLine}{Exception} ]"
        }
      }
    ]
  }

Than you need to add this config in C# code.

var _logger = new LoggerConfiguration()
            .ReadFrom
            .Configuration(configuration)
            .Enrich
            .FromLogContext()
            .CreateLogger();
        services.AddLogging(logBuilder => logBuilder.AddSerilog(_logger));


configuration is an instance of IConfiguration, u will find builder.Configuration
services --> builder.Services
Amentos
  • 71
  • 8
-1

This is how I did it:

private readonly Serilog.ILogger _logger; //= Log.ForContext( "Name", "Weather" );

public WeatherForecastController() {
  string subPath = Path.Combine( DateTime.Now.ToString( "yyyy" ), DateTime.Now.ToString( "MM" ) ) + $"/{DateTime.Now.ToString("dd")}_Weather";
  _logger = Log.ForContext( "Name", subPath );
}

  .UseSerilog( ( hostingContext, loggerConfiguration ) => loggerConfiguration
    .ReadFrom.Configuration( hostingContext.Configuration )
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.Map(
      "Name",
      "Request",
      ( name, wt ) => {
        if (name == "Request")
          wt.RollingFile( Path.Combine( $"{hostingContext.Configuration["LogPath"]}/{{Date}}-{name}.txt" ) );
        else
          wt.File( $"{hostingContext.Configuration["LogPath"]}/{name}.txt" );
      } )
  );   
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Garrod Ran
  • 318
  • 3
  • 5
  • Welcome! Please note that the [policy](https://stackoverflow.blog/2009/07/23/non-english-question-policy/) is that [questions and answers need to be in English](https://meta.stackexchange.com/questions/13676/do-posts-have-to-be-in-english-on-stack-exchange). Please also [explain while your code is a solution](https://meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). Some additional context helps a lot for others who will look at this later to understand why and how this solves the problem. – zsltg May 15 '20 at 07:14