Git Product home page Git Product logo

serilog-extensions-logging-file's Introduction

Serilog.Extensions.Logging.File NuGet Pre Release Join the chat at https://gitter.im/serilog/serilog Build status

This package makes it a one-liner - loggingBuilder.AddFile() - to configure top-quality file logging for ASP.NET Core apps.

  • Text or JSON file output
  • Files roll over on date; capped file size
  • Request ids and event ids included with each message
  • Log writes are performed asynchronously
  • Files are periodically flushed to disk (required for Azure App Service log collection)
  • Fast, stable, battle-proven logging code courtesy of Serilog

You can get started quickly with this package, and later migrate to the full Serilog API if you need more sophisticated log file configuration.

Getting started

1. Add the NuGet package as a dependency of your project either with the package manager or directly to the CSPROJ file:

<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />

2. In your Program class, configure logging on the host builder, and call AddFile() on the provided loggingBuilder:

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webHost =>
    {
        webHost.UseStartup<Startup>();
    })
    .ConfigureLogging((hostingContext, loggingBuilder) =>
    {
        loggingBuilder.AddFile("Logs/myapp-{Date}.txt");
    })
    .Build();

Or, alternatively, with Minimal APIs:

    var builder = WebApplication.CreateBuilder(args);

    builder.Logging.AddFile("Logs/myapp-{Date}.txt");
    // Add other services to the container.
    <...>

    var app = builder.Build();
    <...>

Done! The framework will inject ILogger instances into controllers and other classes:

class HomeController : Controller
{
    readonly ILogger<HomeController> _log;

    public HomeController(ILogger<HomeController> log)
    {
        _log = log;
    }

    public IActionResult Index()
    {
        _log.LogInformation("Hello, world!");
    }
}

The events will appear in the log file:

2016-10-18T11:14:11.0881912+10:00 0HKVMUG8EMJO9 [INF] Hello, world! (f83bcf75)

File format

By default, the file will be written in plain text. The fields in the log file are:

Field Description Format Example
Timestamp The time the event occurred. ISO-8601 with offset 2016-10-18T11:14:11.0881912+10:00
Request id Uniquely identifies all messages raised during a single web request. Alphanumeric 0HKVMUG8EMJO9
Level The log level assigned to the event. Three-character code in brackets [INF]
Message The log message associated with the event. Free text Hello, world!
Event id Identifies messages generated from the same format string/message template. 32-bit hexadecimal, in parentheses (f83bcf75)
Exception Exception associated with the event. Exception.ToString() format (not shown) System.DivideByZeroException: Attempt to divide by zero\r\n\ at...

To record events in newline-separated JSON instead, specify isJson: true when configuring the logger:

loggingBuilder.AddFile("Logs/myapp-{Date}.txt", isJson: true);

This will produce a log file with lines like:

{"@t":"2016-06-07T03:44:57.8532799Z","@m":"Hello, world!","@i":"f83bcf75","RequestId":"0HKVMUG8EMJO9"}

The JSON document includes all properties associated with the event, not just those present in the message. This makes JSON formatted logs a better choice for offline analysis in many cases.

Rolling

The filename provided to AddFile() should include the {Date} placeholder, which will be replaced with the date of the events contained in the file. Filenames use the yyyyMMdd date format so that files can be ordered using a lexicographic sort:

log-20160631.txt
log-20160701.txt
log-20160702.txt

To prevent outages due to disk space exhaustion, each file is capped to 1 GB in size. If the file size is exceeded, events will be dropped until the next roll point.

Message templates and event ids

The provider supports the templated log messages used by Microsoft.Extensions.Logging. By writing events with format strings or message templates, the provider can infer which messages came from the same logging statement.

This means that although the text of two messages may be different, their event id fields will match, as shown by the two "view" logging statements below:

2016-10-18T11:14:26.2544709+10:00 0HKVMUG8EMJO9 [INF] Running view at "/Views/Home/About.cshtml". (9707eebe)
2016-10-18T11:14:11.0881912+10:00 0HKVMUG8EMJO9 [INF] Hello, world! (f83bcf75)
2016-10-18T11:14:26.2544709+10:00 0HKVMUG8EMJO9 [INF] Running view at "/Views/Home/Index.cshtml". (9707eebe)

Each log message describing view rendering is tagged with (9707eebe), while the "hello" log message is given (f83bcf75). This makes it easy to search the log for messages describing the same kind of event.

Additional configuration

The AddFile() method exposes some basic options for controlling the connection and log volume.

Parameter Description Example value
pathFormat Filename to write. The filename may include {Date} to specify how the date portion of the filename is calculated. May include environment variables. Logs/log-{Date}.txt
minimumLevel The level below which events will be suppressed (the default is LogLevel.Information). LogLevel.Debug
levelOverrides A dictionary mapping logger name prefixes to minimum logging levels.
isJson If true, the log file will be written in JSON format. true
fileSizeLimitBytes The maximum size, in bytes, to which any single log file will be allowed to grow. For unrestricted growth, passnull. The default is 1 GiB. 1024 * 1024 * 1024
retainedFileCountLimit The maximum number of log files that will be retained, including the current log file. For unlimited retention, pass null. The default is 31. 31
outputTemplate The template used for formatting plain text log output. The default is {Timestamp:o} {RequestId,13} [{Level:u3}] {Message} ({EventId:x8}){NewLine}{Exception} {Timestamp:o} {RequestId,13} [{Level:u3}] {Message} {Properties:j} ({EventId:x8}){NewLine}{Exception}

appsettings.json configuration

The file path and other settings can be read from JSON configuration if desired.

In appsettings.json add a "Logging" property:

{
  "Logging": {
    "PathFormat": "Logs/log-{Date}.txt",
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Information"
    }
  }
}

And then pass the configuration section to the AddFile() method:

loggingBuilder.AddFile(hostingContext.Configuration.GetSection("Logging"));

In addition to the properties shown above, the "Logging" configuration supports:

Property Description Example
Json If true, the log file will be written in JSON format. true
FileSizeLimitBytes The maximum size, in bytes, to which any single log file will be allowed to grow. For unrestricted growth, passnull. The default is 1 GiB. 1024 * 1024 * 1024
RetainedFileCountLimit The maximum number of log files that will be retained, including the current log file. For unlimited retention, pass null. The default is 31. 31
OutputTemplate The template used for formatting plain text log output. The default is {Timestamp:o} {RequestId,13} [{Level:u3}] {Message} ({EventId:x8}){NewLine}{Exception} {Timestamp:o} {RequestId,13} [{Level:u3}] {Message} {Properties:j} ({EventId:x8}){NewLine}{Exception}

Using the full Serilog API

This package is opinionated, providing the most common/recommended options supported by Serilog. For more sophisticated configuration, using Serilog directly is recommened. See the instructions in Serilog.AspNetCore to get started.

The following packages are used to provide loggingBuilder.AddFile():

If you decide to switch to the full Serilog API and need help, please drop into the Gitter channel or post your question on Stack Overflow.

serilog-extensions-logging-file's People

Contributors

chrismcna avatar dependabot[bot] avatar kellystuard avatar maximrouiller avatar merbla avatar micdenny avatar mmarinchenko avatar nblumhardt avatar poke avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serilog-extensions-logging-file's Issues

Configuration change token support

Hi,
It seems that the change token handling isn't implemented in this extension. At least I couldn't find it in code and I found it while playing with it and changing configuration but nothing happend ;)

Is this something you are going to add?
thanks
M

I can't make LogLevel work

Hi,
I'm trying the extension, and it's working great, but I can't get Debug Levels logged.
I've settled up the app.settings like this:

"Logging": {
    "PathFormat": "Logs/log-{Date}.txt",
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Information"
    }
  },

And the Startup.cs like this:
loggerFactory.AddFile(Configuration.GetSection("Logging"));

I'm trying really simple from a controller:
_logger.LogDebug("TestController");

But the log is not in the file. If I change
_logger.LogDebug("TestController") to _logger.LogInformation("TestController"); the log shows in the log file as expected.

What I'm doing wrong?

Thanks for your help.

Means to troubleshoot/debug logging?

i am registering serilog file logger via Microsoft.Extensions.Logging in my Xamarin.Forms AppContainer like this:

builder
	.Register(handler => LoggerFactory.Create(log =>
	{
		log.AddFile("log.txt");
	}))
	.As<ILoggerFactory>()
	.SingleInstance()
	.AutoActivate();

builder
	.RegisterGeneric(typeof(Logger<>))
	.As(typeof(ILogger<>))
	.SingleInstance();

and try to write some log data later on like this:

var logger = AppContainer.Resolve<ILogger<App>>();
logger.LogCritical("test");

but for some reason i neither get any error nor a log file which begs the question: how can i troubleshoot this to find out what's wrong?

Output categories in log file

The current log string format doesn't output the category of the entry - at least not by default, but maybe I'm overlooking a configuration option somewhere?

If output of log item category is not supported today, are there any plans for it in the future?

Unable to add metadata

I'm using Serilog.Extensions.Logging.File nuget package Version=2.0.0 in my AspNet Core 3.1 app.
This is what I have in my Program.cs file:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
               .ConfigureLogging((hostingContext, builder) =>
                {
                    builder.AddFile(hostingContext.Configuration.GetSection("Serilog"));
                    builder.AddSerilog(dispose: true);
                })

This is what I have in my appsettings.json

"Serilog": {
    "Using": [ "Serilog.Sinks.RollingFile" ],
    "Enrich": [
      "FromLogContext"
    ],
    "PathFormat": "Logs/myapp-{Date}.txt",
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "Json": false,
    "FileSizeLimitBytes": 1000000,
    "RetainedFileCountLimit": 3,
    "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}Properties: {Properties}{NewLine}MachineName: {MachineName}{NewLine}Application: {Application}{NewLine}{Exception}-------------------------------------------------------------------{NewLine}",
    "Properties": {
      "Application": "XWRA",
      "MachineName": "%COMPUTERNAME%"
    }
  }

It generates the txt file but not metadata of Application and Machine name.
I'm using Windows machine.
Am I missing something?

No Way To Flush Logger At End Of Console App Lifetime

There doesn't seem to be a way to flush the logger's contents to file at the end of the lifetime of a console app.

To reproduce, create a dotnet core console app and log a few lines. Then let the program run to its end. More often than not, it won't log anything.

Add a Console.ReadKey() to the end of your program, and you'll see this will make the logger flush itself, because it's granted some time to do so.

The Log.CloseAndFlush() method is not available when you are only using the file logging extension method.

Even if it were, it would need to have a logger assigned to Log.Logger. But its type is not compatible with dotnet core's logger type as used in this snippet:

serviceCollection
	.AddLogging()
	.AddSingleton(
		new LoggerFactory()
			.AddFile(@"Logs/myapp-{Date}.txt")
			.AddConsole()
			.AddDebug()
);

It would be nice if the Serilog logger could flush itself on finalize.

I believe this is how log4net does it, since I never had any problems with that.

Logger is not disposed along with ServiceProvider

Repro: https://github.com/aleksey-s902/SerilogProviderNotDisposedRepro

        static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                .AddLogging(builder =>
                {
                    builder.AddFile("test.log");
                })
                .BuildServiceProvider();

            var logger = serviceProvider.GetService<ILogger<Program>>();
            logger.LogError("test");
            
            serviceProvider.Dispose();
            // Thread.Sleep(5000);
        }

Problem with this code: the log file isn't written. There is obviously a race condition because if I uncomment Thread.Sleep, the log file appears correctly. My understanding of what happening there is:

  • AddFile adds an async file writer which runs in a background thread
  • Application shuts down before the background thread has a chance to write the log file
  • Normally, this is prevented by disposing logger before shutdown. I would expect that in this case ServiceProvider would dispose the logger. However, that isn't happening.

As to why it isn't happening: I suppose that's caused by the same reason as aspnet/Hosting#1466. AddSerilog register an instance of SerilogLoggerProvider, and ServiceProvider won't dispose anything added as an instance.

Workaround: dispose the logger provider manually:

serviceProvider.GetService<ILoggerProvider>().Dispose();

DNC 3.1 on Unbuntu Missing Method Exception

  • Issue is not seen on windows
  • Issue is only seen on my server (Linux Unbuntu running DNC 3.1)
  • Removing Serilog fixes the issue
  • Stack trace below

root:~/SimpleOffice# dotnet SimpleOffice.dll
Application startup exception: System.MissingMethodException: Method not found: 'Microsoft.Extensions.Logging.ILoggerFactory Microsoft.Extensions.Logging.FileLoggerExtensions.AddFile(Microsoft.Extensions.Logging.ILoggerFactory, System.String, Microsoft.Extensions.Logging.LogLevel, System.Collections.Generic.IDictionary2<System.String,Microsoft.Extensions.Logging.LogLevel>, Boolean, System.Nullable1, System.Nullable1<Int32>)'. at SimpleOffice.Startup.ConfigureLogger(ILoggerFactory loggerFactory, IHttpContextAccessor http) at SimpleOffice.Startup.Configure(IApplicationBuilder app, IServiceScopeFactory factory, IWebHostEnvironment env, IHttpContextAccessor http, ILoggerFactory loggerFactory) in D:\Projects\SimpleSys\SimpleOffice\SimpleOffice\SimpleOffice\Startup.cs:line 138 at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder) at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder) at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app) at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder) at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app) at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication() crit: Microsoft.AspNetCore.Hosting.WebHost[6] Application startup exception System.MissingMethodException: Method not found: 'Microsoft.Extensions.Logging.ILoggerFactory Microsoft.Extensions.Logging.FileLoggerExtensions.AddFile(Microsoft.Extensions.Logging.ILoggerFactory, System.String, Microsoft.Extensions.Logging.LogLevel, System.Collections.Generic.IDictionary2<System.String,Microsoft.Extensions.Logging.LogLevel>, Boolean, System.Nullable1<Int64>, System.Nullable1)'.
at SimpleOffice.Startup.ConfigureLogger(ILoggerFactory loggerFactory, IHttpContextAccessor http)
at SimpleOffice.Startup.Configure(IApplicationBuilder app, IServiceScopeFactory factory, IWebHostEnvironment env, IHttpContextAccessor http, ILoggerFactory loggerFactory) in D:\Projects\SimpleSys\SimpleOffice\SimpleOffice\SimpleOffice\Startup.cs:line 138
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication()
Unhandled exception. System.MissingMethodException: Method not found: 'Microsoft.Extensions.Logging.ILoggerFactory Microsoft.Extensions.Logging.FileLoggerExtensions.AddFile(Microsoft.Extensions.Logging.ILoggerFactory, System.String, Microsoft.Extensions.Logging.LogLevel, System.Collections.Generic.IDictionary2<System.String,Microsoft.Extensions.Logging.LogLevel>, Boolean, System.Nullable1, System.Nullable`1)'.
at SimpleOffice.Startup.ConfigureLogger(ILoggerFactory loggerFactory, IHttpContextAccessor http)
at SimpleOffice.Startup.Configure(IApplicationBuilder app, IServiceScopeFactory factory, IWebHostEnvironment env, IHttpContextAccessor http, ILoggerFactory loggerFactory) in D:\Projects\SimpleSys\SimpleOffice\SimpleOffice\SimpleOffice\Startup.cs:line 138
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
at SimpleOffice.Program.Main(String[] args) in D:\Projects\SimpleSys\SimpleOffice\SimpleOffice\SimpleOffice\Program.cs:line 30

ASP Net Core Logs written even if "Microsoft.*"="None" (appsettings.json)

Hi,

I downloaded your repository and launched the example project and saw a lot of noisy logs were generated by the aspnetcore itself.
I tried to set the Microsoft entry of the appsettings.json to None but it didn't change anything.
Must I use your UseSerilogRequestLogging even if I just don't want this kind of logs?

{
  "Logging": {
    "PathFormat": "Logs/log-{Date}.txt",
    "OutputTemplate": "{Timestamp:o} {RequestId,13} [{Level:u3}] {Message} ({EventId:x8}) {Properties:j}{NewLine}{Exception}",
    "IncludeScopes": true,
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.*": "None"
    }
  }
}

Ability to configure the message template

It would be super nice if we were able to configure the message template instead of it being hard coded here.

I know that this library is opinionated and that the full serilog is recommended for more complex use cases, but this one is very easy to do with great benefits. I don't see myself ever needing the full serilog, but changing the message template would be very nice to have.

Logging stopped after upgrading to aspnetcore 2.0

We have a project that we upgraded to aspnetcore 2.0. We have 2 logging providers, a console and a serilog file. After the upgrade (we didn't change anything related to logging at all), logging to a file stopped completely, the console logging is still working.

I updated this package to 2.0 preview, but the same still happened.

The config code is very simple:

loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddFile(Configuration.GetSection("Serilog"));

Rolling on size

Is there a way of getting the log files to roll on max size exceeded?

Cheers!

ReadMe Package Reference Version

The ReadMe says to add the following package reference:

<PackageReference Include="Serilog.Extensions.Logging.File" Version="2.0.0" />

But only version 1.1.0 is out.

append to log file

Hi, I was success output log file
But I want add some line to log file
I try add in code
Log.Logger.Information("Hello"); //global Log
but in log file still don't have it

Or I need declare at every class this line
static readonly ILogger Log = Serilog.Log.ForContext<>();

Support `AddFile()` on `ILoggingBuilder`

Didnt even get past the first line of instructions after installing from NuGet.
Can someone help please???

I have an issue where ILoggingBuilder does not contain a definition for AddFile.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace SH.Pathology.Pttc.API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var webHost = WebHost.CreateDefaultBuilder(args)
                .ConfigureLogging((context, loggingBuilder) =>
                {
                    loggingBuilder.AddFile("");
                })
                .UseStartup<Startup>();

            webHost.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
            {
                if (hostingContext.HostingEnvironment.IsDevelopment())
                {
                    configurationBuilder.AddJsonFile("appsettings.Development.json", true);
                }
                else if(hostingContext.HostingEnvironment.IsStaging())
                {
                    configurationBuilder.AddJsonFile("appsettings.Staging.json", true);
                }
                else
                {
                    configurationBuilder.AddJsonFile("appsettings.Production.json", true);
                }
            });

            return webHost;
        }
    }
}

Need to be able to specify dispose:true

I tried to use this in a console application but found that if I logged and exited immediately then the log file was not flushed, there was no opportunity to specify the dispose.
I ended up doing the below in the end.

// Set up Serilog
Log.Logger = new LoggerConfiguration()
	.WriteTo.RollingFile(logFilename)
        .CreateLogger();

// Add logging
services.AddSingleton(
	new LoggerFactory()
		.AddSerilog(dispose:true)
		.AddConsole(loggingConfiguration)
		.AddDebug(LogLevel.Trace)
);

String arguments for message are enclosed in double quotes - different from other loggers

Within the Asp.Net Core logging infrastructure, the default rendering of format arguments should be the same. Example:

LogInformation("This is {0}", "an error") is expected to render as: This is an error

However, with Serilog it renders as: This is "an error"

Although this can be fixed supposedly by adding the :l specifier, I do not want to add Serilog specific modifiers, as I have other loggers that are used with the same messages concurrently.

Can't set shared property for rollingfile settings

We seem to be able to configure all rollingfile settings except for file sharing. The code for some reason has a preprocessor directive to set it to true or false if SHARED is defined, but it is not and there is no way to set that via code (obviously). We should be able to set this property.

CVE-2019-0820 on System.Text.RegularExpressions 4.1.0 and 4.3.0

Description

Per https://nvd.nist.gov/vuln/detail/CVE-2019-0820, there's a ReDoS vulnerability in System.Text.RegularExpressions 4.3.0, which is being referenced by Serilog 2.5.0 under .NET Standard. The vulnerability is also present in version 4.1.0 even though the advisory does not state that.

Explanation from Sonatype:

The System.Text.RegularExpressions package contains a Regular Expression Denial of Service (ReDoS) vulnerability. The System.Text.RegularExpressions.dll file does not properly implement a timeout when handling regular expressions. An attacker can exploit this with a maliciously crafted regular expression string, which when processed could use excessive resources and cause an application crash, resulting in a Denial of Service (DoS).

Advisory Deviation Notice: The Sonatype security research team discovered that the vulnerability is present in version 4.0.12-rc2-24027 until 4.1.0, not just version 4.3.0 as the advisory states.

System.Text.RegularExpressions 4.3.1 does not have this vulnerability.

I examined the Serilog.nuspec file to confirm that 4.1.0 is being referenced. Assuming the .nuspec is being autogenerated by dotnet pack, I'm guessing the reason 4.1.0 is being referenced rather than 4.3.1 is because of the "lowest applicable version" behavior1.

Reproduction
Create a .NET Standard 2.0 project, reference Serilog 2.5.0, and build the project. Confirm that System.Text.RegularExpressions 4.1.0 is the version that is referenced.

Expected behavior
N/A

Relevant package, tooling and runtime versions
Serilog 2.5.0 on Windows with .NET Framework 4.8 but referenced via a .NET Standard 2.0 project.

Additional context
N/A

Footnotes

  1. https://docs.microsoft.com/en-us/nuget/concepts/dependency-resolution โ†ฉ

LogLevel.None not respected for Microsoft

With this configuration...

"File": { "PathFormat": "Logs/MyLog_{Date}.txt", "LogLevel": { "Default": "Debug", "System": "None", "Microsoft": "None" } }

...Information level messages from Microsoft assemblies are still getting through. A temp workaround we are using is to set Microsoft and System to Critical.

.NET 6 readme update

Hi everyone, first of all thank you very much for your contribution with this package.

I just wanted to remind you to update the readme for .NET 6 users.

In program.cs, it is still very easy to configure logging:

var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddFile("Logs/webapp.txt");

Thank you again

How to reconfigure after AppSettings.json reloaded?

I use loggerFactory.AddFile(AppSettings.Configuration.GetSection("Logging:Serilog")); in Startup.Configure, when appsettings.json file changed, i want update the settings of serilog.
I use ChangeToken.OnChange for response the changing:

ChangeToken.OnChange(() => AppSettings.Configuration.GetReloadToken(), env_ =>
{
    //how to reconfigure serilog?
}, env);

Request id doesn't seem to be correct

My ASP.NET Core web API uses Serilog.Extensions.Logging.File version 1.1.0 and here is the sample of a log file generated from it
myLog-20180703.log
I had "The operation timed out" exception recorded under Request id = 0HLF0SCB4K08A. I know that web request to my web API makes only one call to https://_ _ /products/(...)? _ _ URL. However, I see call to this URL in line 1, 4, 9 and 16. What does a code after : means? Is it a part of Request id? Please explain.

No rotation if size limit hits maximum

My expectation is that a new file should be written if the size limit reaches the maximum.
Instead log-messages are lost.

I use the component in a asp core 2 project. Configuration is in appsettings.json.

Option to specify a custom format for the {Date} placeholder in the file name?

Hi, I noticed that placing the {Date} placeholder in the pathFormat argument of the AddFile() extension method will make the lib put the current date in the format "yyyyMMdd" into the name.

Is there an option to specify a customized format. Other log files in my system use underlines between the poritions, i.e. "yyyy_MM_dd" and I'd like serilog to do the same.

Thanks

Current User support

I'm logging the current user once per request. Thus, I'm able to find a single request of a specific user, but it would be nice to just filter log entries by the current user.

It already seems to be possible using some kind of middleware ceremony, but having a "one line" solution here would be really nice.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.