You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
BookingHeChuan/Myshipping.Core/Logging/Component/LoggingFileComponent.cs

68 lines
2.3 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using Furion.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Text;
namespace Myshipping.Core;
/// <summary>
/// 日志写入文件的组件
/// </summary>
public sealed class LoggingFileComponent : IServiceComponent
{
public void Load(IServiceCollection services, ComponentContext componentContext)
{
// 日志记录
// 每天创建一个日志文件
services.AddLogging(builder =>
{
builder.AddFile("logs/error/{0:yyyyMMdd}_.log", options =>
{
SetLogOptions(options, LogLevel.Error);
});
builder.AddFile("logs/info/{0:yyyyMMdd}_.log", options =>
{
SetLogOptions(options, LogLevel.Information);
});
builder.AddFile("logs/warn/{0:yyyyMMdd}_.log", options =>
{
SetLogOptions(options, LogLevel.Warning);
});
});
}
private void SetLogOptions(FileLoggerOptions options, LogLevel logLevel)
{
options.WriteFilter = (logMsg) =>
{
return logMsg.LogLevel == logLevel;
};
options.FileNameRule = fileName =>
{
return string.Format(fileName, DateTime.UtcNow);
};
options.FileSizeLimitBytes = 5000 * 1024;
options.MessageFormat = (logMsg) =>
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"[{logMsg.LogLevel}] [{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")}] [{logMsg.LogName}] [{System.Threading.Thread.CurrentThread.ManagedThreadId}] ");
stringBuilder.AppendLine($" {logMsg.Message}");
if (logMsg.Exception != null)
{
stringBuilder.AppendLine(logMsg.Exception.Message);
stringBuilder.AppendLine(logMsg.Exception.StackTrace);
}
if (logMsg.Context != null && logMsg.Context.Properties != null && logMsg.Context.Properties.Count > 0)
{
foreach (var prop in logMsg.Context.Properties)
{
stringBuilder.AppendLine($"{prop.Key}{prop.Value}");
}
}
return stringBuilder.ToString();
};
}
}