Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add file logging to ASP.NET Core apps in one line of code.

License

NotificationsYou must be signed in to change notification settings

serilog/serilog-extensions-logging-file

Repository files navigation

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 ofSerilog

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

Versioning

This package tracks the version of ASP.NET Core that it targets. If you're using 9.x.x of ASP.NET Core, use 9.x.x ofSerilog.Extensions.Logging.File, and so on.

If the version you're using doesn't have a correspondingSerilog.Extensions.Logging.File release, target v3.x of this package.

Getting started

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

<PackageReferenceInclude="Serilog.Extensions.Logging.File"Version="9.0.0" />

2. In yourProgram class, configure logging on the host builder, and callAddFile() on the providedILoggingBuilder:

builder.Services.AddLogging(logging=>{logging.AddFile("Logs/myapp-{Date}.txt");});

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

classHomeController:Controller{readonlyILogger<HomeController>_log;publicHomeController(ILogger<HomeController>log){_log=log;}publicIActionResultIndex(){_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:

FieldDescriptionFormatExample
TimestampThe time the event occurred.ISO-8601 with offset2016-10-18T11:14:11.0881912+10:00
Request idUniquely identifies all messages raised during a single web request.Alphanumeric0HKVMUG8EMJO9
LevelThe log level assigned to the event.Three-character code in brackets[INF]
MessageThe log message associated with the event.Free textHello, world!
Event idIdentifies messages generated from the same format string/message template.32-bit hexadecimal, in parentheses(f83bcf75)
ExceptionException 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, specifyisJson: 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 toAddFile() should include the{Date} placeholder, which will be replaced with the date of the events contained in the file. Filenames use theyyyyMMdd date format so that files can be ordered using a lexicographic sort:

log-20160631.txtlog-20160701.txtlog-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 byMicrosoft.Extensions.Logging. By writing events with format strings ormessage 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, theirevent 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

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

ParameterDescriptionExample value
pathFormatFilename 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
minimumLevelThe level below which events will be suppressed (the default isLogLevel.Information).LogLevel.Debug
levelOverridesA dictionary mapping logger name prefixes to minimum logging levels.
isJsonIf true, the log file will be written in JSON format.true
fileSizeLimitBytesThe 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
retainedFileCountLimitThe maximum number of log files that will be retained, including the current log file. For unlimited retention, passnull. The default is31.31
outputTemplateThe 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.

Inappsettings.json add a"Logging" property:

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

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

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

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

PropertyDescriptionExample
JsonIftrue, the log file will be written in JSON format.true
FileSizeLimitBytesThe 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
RetainedFileCountLimitThe maximum number of log files that will be retained, including the current log file. For unlimited retention, passnull. The default is31.31
OutputTemplateThe 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 recommended. See the instructions inSerilog.AspNetCore to get started.

The following packages are used to provideloggingBuilder.AddFile():

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

About

Add file logging to ASP.NET Core apps in one line of code.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors9


[8]ページ先頭

©2009-2025 Movatter.jp