Serilog
Serilog
serilog日志
serilog日志简单方法
1安装包
第一个是基础的配置,第二个包是集成Serilog日志记录器的扩展包,简化在.NET应用程序中集成和配置Serilog的过程。第三个是保存在文档中
2 配置文件
public static void AddSerilog(this WebApplicationBuilder builder)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // 排除Microsoft的日志
.Enrich.FromLogContext() // 注册日志上下文
.WriteTo.Logger(configure => configure // 输出到文件
.MinimumLevel.Debug()
.WriteTo.File(
$"logs\\log.txt", // 单个日志文件,总日志,所有日志存到这里面
rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u20}] {Message:lj}{NewLine}"
)
)
.CreateLogger();
builder.Host.UseSerilog();
}
Program:
//全局异常计入日志
serilog存入数据库并到txt文档分表,并显示
- 配置文档,注入,用哪个装那个
/// <summary>
/// Serilog日志
/// </summary>
/// <param name="builder"></param>
public static void AddSerilog(this WebApplicationBuilder builder)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
.Build(); // 读取配置文件
var connectionString = configuration["ConnectionStrings:Con"].Trim(); // 获取默认的数据库连接字符串
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration) // 读取配置文件中的配置
.WriteTo.Console(theme: AnsiConsoleTheme.Code) // 写入控制台输出,且使用 AnsiConsoleTheme.Code 主题
.WriteTo.Map( // 动态配置
keyPropertyName: "Name", // 键属性名
defaultKey: "0", // 默认键值
configure: (name, wt) => wt.Logger(lc => lc // 配置单个log
.WriteTo.MSSqlServer( // 写入MSSQL
connectionString: connectionString, // 使用默认的数据库连接字符串
sinkOptions: new MSSqlServerSinkOptions
{
TableName = $"LogEvents_{name}", // 动态表名
AutoCreateSqlTable = true // 自动创建表
})
.WriteTo.File($"logs\\log_{name}.txt", rollingInterval: RollingInterval.Day)) // 写入日志文件
)
.CreateLogger(); // 创建log
}
"Serilog": {
"MinimumLevel": "Information" //日志输出最小级别
},最小输出级别
读取文档方法
/// <summary>
/// 日志文本读取
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Get(string? logdate, string? name, int page = 1, int size = 15)
{
string logFilePath = $"logs\\log_1{DateTime.Now:yyyyMMdd}.txt";
List<LogEntry> logEntries = new List<LogEntry>();
try
{
string[] logLines = System.IO.File.ReadAllLines(logFilePath);
foreach (string logLine in logLines)
{
string[] logParts = logLine.Split(' ');
string timestamp = logParts[0].Replace("-", "")+ logParts[1].Replace(":","").Replace(".","");
string level = logParts[3];
string message = logParts[5];
string username= logParts[4];
DateTime timedate = DateTime.Parse(logParts[0]+ " "+logParts[1]);
LogEntry entry = new LogEntry
{
Timestamp = timestamp,
Level = level,
Message = message,
username= username,
TimeDate=timedate,
};
logEntries.Add(entry);
}
}
catch (IOException e)
{
// 在实际应用中,你可能需要进一步处理文件读取失败的情况
return StatusCode(500, $"读取日志文档失败:{e.Message}");
}
if (!string.IsNullOrEmpty(logdate))
{
DateTime targetDate = DateTime.Parse(logdate);
DateTime startOfDay = targetDate.Date;
DateTime endOfDay = targetDate.Date.AddDays(1).AddSeconds(-1);
logEntries = logEntries.Where(t => t.TimeDate >= startOfDay && t.TimeDate <= endOfDay).ToList();
}
if (!string.IsNullOrEmpty(name))
{
logEntries = logEntries.Where(t => t.username.Contains(name)).ToList();
}
int totalCount = logEntries.Count();
int pageCount = (int)Math.Ceiling(totalCount * 1.0 / size);
logEntries = logEntries.Skip((page - 1) * size).Take(size).ToList();
return Ok(new
{
logEntries,
totalCount,
pageCount,
});
}