今天在看项目的日志记录功能,比较疑惑为什么项目中有的地方使用 Logger< T > _logger 然后又在资源文件下看见日志的第三方库 Serilog
解答:
ASP.NET Core Build-in Logging
ASP.NET Core 提供了 Logging 的抽象接口, third party 都会依据抽象来做实现. ASP.NET Core 自己也实现了一套简单的 log, 它只能 log to console. 不能 log to file.只能输出到控制台,但是不能输出到文件
所以绝大部分项目都会搭配一个 third party library, 比如 Serilog.
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.AspNetCore
using System;
using System.IO;
using Serilog;
using Serilog.Events;namespace UIH.RT.HRuiJin.Log
{public class SerilogByMySelf : ILogger // 看吧serilog要接盘内置的log{private readonly Serilog.Core.Logger _logger;private const string logFilePath = "文件路径.txt";protected string logFileFolder = "日志文件夹的名字";protected string date = DateTime.Today.ToString("yyyyMMdd");protected virtual string LogFilePath => Path.Combine(logFolderName, date, logFilePath);public SerilogByMySelf(){_logger = new LoggerConfiguration().MinimumLevel.Verbose().MinimumLevel.Override("Microsoft", LogEventLevel.Information).MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning).WriteTo.Async("写你的文件路径").CreateLogger();}// 接盘之后也可以加自定义操作public void Warning(object obj){_logger.Warning(obj.ToString());}}
}
解决答案REF:c# - Use Serilog with Microsoft.Extensions.Logging.ILogger - Stack Overflow
public class Program{public static int Main(string[] args){SeriLog.Logger = new SerilogFucker();internal static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()}).UseSerilog(); // 这一行最重要!!!}
关于内置logger的资料 :ASP.NET Core 源码学习之 Logging[1]:Introduction - 雨夜朦胧 - 博客园
1. 对于微服务的调用记录,存储方式如何? 文件 or 数据库
2. 如果是文件,改代码最方便的方法是新建一个 “Api_History” 文件,在调用proxy api时候对每一个方法手动地添加 _logger.info( )
3. 或者适配器模式,抽象出一个适配器类 or 桥接类 or super class虚方法?
4.或者ABP的审计更合适?
2022/12/1
得,问了问TeamLeader, 方法函数内纯手打就行了。直接干就完事了