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}|{Exception}{NewLine}";
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");