Serilog.Extensions.Logging.File

This package makes it a one-liner - loggerFactory.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
  • Writes are performed on a background thread
  • 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:

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

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

  1. Host.CreateDefaultBuilder(args)
  2. .ConfigureLogging((hostingContext, loggingBuilder) =>
  3. {
  4. // loggingBuilder.AddFile("Logs/Logs_{Date}.txt");
  5. loggingBuilder.AddFile(hostingContext.Configuration.GetSection("Logging"));
  6. })
  7. .ConfigureWebHostDefaults(webBuilder =>
  8. {
  9. webBuilder.UseStartup<Startup>();
  10. });

3. Add a custom excetion filter as a global exception handler:

  1. public class GlobalExceptionFilter : IExceptionFilter
  2. {
  3. private readonly ILogger<GlobalExceptionFilter> _logger;
  4. public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
  5. {
  6. _logger = logger;
  7. }
  8. public void OnException(ExceptionContext context)
  9. {
  10. var loggingBuilder = new StringBuilder();
  11. if (context.HttpContext.Request.GetDisplayUrl() != null)
  12. loggingBuilder.AppendLine($"\tUrl: {context.HttpContext.Request.GetDisplayUrl()}");
  13. loggingBuilder.AppendLine($"\tIp: {context.HttpContext.Connection.RemoteIpAddress}");
  14. #if DEBUG
  15. foreach (var key in context.HttpContext.Request.Headers.Keys)
  16. {
  17. loggingBuilder.AppendLine($"\t{key}: {context.HttpContext.Request.Headers[key]}");
  18. }
  19. #endif
  20. loggingBuilder.AppendLine($"\tError Message: {context.Exception.Message}");
  21. if (context.Exception.InnerException != null)
  22. {
  23. PrintInnerException(context.Exception.InnerException, loggingBuilder);
  24. }
  25. loggingBuilder.AppendLine($"\tError HelpLink: {context.Exception.HelpLink}");
  26. loggingBuilder.AppendLine($"\tError StackTrace: {context.Exception.StackTrace}");
  27. _logger.LogError(loggingBuilder.ToString());
  28. }
  29. public void PrintInnerException(Exception ex, StringBuilder loggingBuilder)
  30. {
  31. loggingBuilder.AppendLine($"\tError InnerMessage: {ex.Message}");
  32. if (ex.InnerException != null)
  33. {
  34. PrintInnerException(ex.InnerException, loggingBuilder);
  35. }
  36. }
  37. }

4. In your Startup class, configure the global exception handler on the ConfigureServices method, so we can catch all unhandled exceptions:

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. ...
  4. services.AddControllersWithViews(options =>
  5. {
  6. options.Filters.Add<GlobalExceptionFilter>();
  7. });
  8. ...
  9. }
  1. public IActionResult Privacy()
  2. {
  3. throw new Exception("Unhandled exception");
  4. return View();
  5. }

5. In your Startup class, add the log directory as static on the Configure method, so we can view the log directory:

  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3. ...
  4. app.UseStaticFiles();
  5. //add the log directory as static, so we can view the log directory
  6. app.UseFileServer(new FileServerOptions()
  7. {
  8. FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Logs")),
  9. RequestPath = new PathString("/Log"),
  10. EnableDirectoryBrowsing = true
  11. });
  12. app.UseRouting();
  13. ...
  14. }

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

  1. class HomeController : Controller
  2. {
  3. readonly ILogger<HomeController> _log;
  4. public HomeController(ILogger<HomeController> log)
  5. {
  6. _log = log;
  7. }
  8. public IActionResult Index()
  9. {
  10. _logger.LogInformation("Hello, world!");
  11. _logger.LogError(new Exception("Custom exception"), "Custom exception");
  12. }
  13. }

The events will appear in the log file:

  1. 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:

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

This will produce a log file with lines like:

  1. {"@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:

  1. log-20160631.txt
  2. log-20160701.txt
  3. 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:

  1. 2016-10-18T11:14:26.2544709+10:00 0HKVMUG8EMJO9 [INF] Running view at "/Views/Home/About.cshtml". (9707eebe)
  2. 2016-10-18T11:14:11.0881912+10:00 0HKVMUG8EMJO9 [INF] Hello, world! (f83bcf75)
  3. 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:

  1. {
  2. "Logging": {
  3. "PathFormat": "Logs/log-{Date}.txt",
  4. "LogLevel": {
  5. "Default": "Debug",
  6. "Microsoft": "Information"
  7. }
  8. }
  9. }

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

  1. loggingBuilder.AddFile(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 AddFile():

ASP.NET Core Logging Solution的更多相关文章

  1. ASP.NET Core Logging in Elasticsearch with Kibana

    在微服务化盛行的今天,日志的收集.分析越来越重要.ASP.NET Core 提供了一个统一的,轻量级的Logining系统,并可以很方便的与第三方日志框架集成.我们也可以根据不同的场景进行扩展,因为A ...

  2. Asp.net core logging 日志

    1 基本概念 Dotnet core 一个重要的特征是 Dependency injection ,中文一般是依赖注入,可以简单理解为一个集合,在应用程序启动时,定义各种具体的实现类型并将其放到集合中 ...

  3. ASP.NET Core 源码学习之 Logging[1]:Introduction

    在ASP.NET 4.X中,我们通常使用 log4net, NLog 等来记录日志,但是当我们引用的一些第三方类库使用不同的日志框架时,就比较混乱了.而在 ASP.Net Core 中内置了日志系统, ...

  4. ASP.NET Core 源码学习之 Logging[3]:Logger

    上一章,我们介绍了日志的配置,在熟悉了配置之后,自然是要了解一下在应用程序中如何使用,而本章则从最基本的使用开始,逐步去了解去源码. LoggerFactory 我们可以在构造函数中注入 ILogge ...

  5. ASP.NET Core 源码学习之 Logging[4]:FileProvider

    前面几章介绍了 ASP.NET Core Logging 系统的配置和使用,而对于 Provider ,微软也提供了 Console, Debug, EventSource, TraceSource ...

  6. 【ASP.NET Core 】ASP.NET Core 源码学习之 Logging[1]:Introduction

    在ASP.NET 4.X中,我们通常使用 log4net, NLog 等来记录日志,但是当我们引用的一些第三方类库使用不同的日志框架时,就比较混乱了.而在 ASP.Net Core 中内置了日志系统, ...

  7. 极简版ASP.NET Core学习路径及教程

    绝承认这是一个七天速成教程,即使有这个效果,我也不愿意接受这个名字.嗯. 这个路径分为两块: 实践入门 理论延伸 有了ASP.NET以及C#的知识以及项目经验,我们几乎可以不再需要了解任何新的知识就开 ...

  8. [转]Using NLog for ASP.NET Core to write custom information to the database

    本文转自:https://github.com/NLog/NLog/issues/1366 In the previous versions of NLog it was easily possibl ...

  9. [转]Setting the NLog database connection string in the ASP.NET Core appsettings.json

    本文转自:https://damienbod.com/2016/09/22/setting-the-nlog-database-connection-string-in-the-asp-net-cor ...

随机推荐

  1. day66 django进阶(2)

    目录 一.choices参数(数据库字段设计常见) 二.MTV与MVC模型 三.多对多三种创建方法 1 全自动 2 纯手动 3 半自动 四.AJax 小 一.choices参数(数据库字段设计常见) ...

  2. day65 django进阶(1)

    目录 一.聚合查询与分组查询 1 聚合查询(aggregate) 2 分组查询(annotate) 二.F与Q查询 1 F查询的三个功能 1.1 能帮助我们直接获取到表中某个字段对应的数据 1.2 获 ...

  3. 【软件测试】Python自动化软件测试算是程序员吗?

    今天早上一觉醒来,突然萌生一个念头,[软件测试]软件测试算是程序员吗?左思右想,总感觉哪里不对.做了这么久的软件测试,还真没深究过这个问题.     基于,内事问百度的准则: 结果……     我刚发 ...

  4. 网课神器之obs-studio的安装使用

    obs-studio 首先,下载obs-studio安装文件,然后点击安装. 建议安装完后直接跳过配置,然后进入文件-设置-通用-系统托盘-勾选"总是最小化到系统托盘,而不是任务栏" ...

  5. 中介者模式(c++实现)

    中介者模式 目录 中介者模式 模式定义 模式动机 UML类图 源码实现 优点 缺点 模式定义 中介者模式(Mediator),用一个中介对象来封装一系列的对象交互.中介者使各对象不需要显示地相互引用, ...

  6. Linux文件搜索

    一.whereis及which命令 这两个命令用来搜索命令的路径(也遵循/etc/updatedb.conf配置文件的筛选规则) whereis 命令名                        ...

  7. 图文详解压力测试工具JMeter的安装与使用

    压力测试是目前大型网站系统的设计和开发中不可或缺的环节,通常会和容量预估等工作结合在一起,穿插在系统开发的不同方案.压力测试可以帮助我们及时发现系统的性能短板和瓶颈问题,在这个基础在上再进行针对性的性 ...

  8. MySQL之字段数据类型和列属性

    数据类型: 对数据进行统一的分类,从系统的角度出发,为了能够使用统一的方式进行管理,更好的利用有限的空间. SQL中将数据类型分成了三大类:数值类型.字符串类型.时间日期类型. 数值型: 数值型数据: ...

  9. BUUCTF-web web1 (无列名注入)

    注册并登录后发现,sql注入,注入点在广告申请的界面.加单引号发现报错 先通过insert插入数据,然后再通过id查询相应的数据,所以是二次注入. 常见报错函数updatexml,floor以及ext ...

  10. laravel 上线部署最佳实践

    nginx  配置 listen 80 default_server; server_name xxxx; index index.php index.html;    优先 index.php ro ...