C#日志记录Serilog使用
Posted 棉晗榜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#日志记录Serilog使用相关的知识,希望对你有一定的参考价值。
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Enrichers;
using Serilog.Events;
using Serilog.Templates;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using WebAPI_Serum.Controllers;
namespace WebAPI_Serum
public class Program
public static void Main(string[] args)
try
const string SerilogOutputTemplate = "Timestamp:yyyy-MM-dd HH:mm:ss.fff|ThreadId|Level:u4|Message:l|ExceptionNewLine";
Log.Logger = new LoggerConfiguration()
.Enrich.WithProperty("Version", "1.0.0")
.Enrich.With(new ThreadIdEnricher())
.Enrich.FromLogContext()
.WriteTo.Console(new ExpressionTemplate(SerilogOutputTemplate))
.WriteTo.File("logs/ALL_" + DateTime.Now.Date.ToString("yyyy-MM-dd") + ".log"
//.WriteTo.File("logs/ALL_log.log"
, outputTemplate: SerilogOutputTemplate
, rollOnFileSizeLimit: true, fileSizeLimitBytes: 1024 * 258 //限制文件最大为258kb
)
//, outputTemplate: SerilogOutputTemplate, rollingInterval: RollingInterval.Day)
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error)
.WriteTo.File("logs/Error_" + DateTime.Now.Date.ToString("yyyy-MM-dd") + ".log",
//.WriteTo.File("logs/Error_log.log",
outputTemplate: SerilogOutputTemplate
, rollOnFileSizeLimit: true, fileSizeLimitBytes: 1024 * 258 //限制文件最大为258kb
))
//outputTemplate: SerilogOutputTemplate, rollingInterval: RollingInterval.Day))
.CreateLogger();
Log.Information("Starting up");
CreateHostBuilder(args).Build().Run();
catch (Exception ex)
Log.Fatal(ex, "Application start-up failed");
finally
Log.CloseAndFlush();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.UseStartup<Startup>()
//.UseUrls("http://*:16586")
;
);
其他类里面手动记录日志:
//错误消息:
Log.Logger.Error($"请求地址:url|发送参数:json|异常消息:msg");
//信息
Log.Logger.Information("获取到样本MQ消息,1122");
以上是关于C#日志记录Serilog使用的主要内容,如果未能解决你的问题,请参考以下文章
C# ASP.NET Core Serilog 添加类名和方法到日志