使用 serilog,我尝试通过 appSettings.json 添加我自己的自定义丰富器,但没有成功。
我完全按照书本,遵循文档。我还遵循了这样的非官方介绍https://www.ctrlaltdan.com/2018/08/14/custom-serilog-enrichers/
上面的介绍适用于金块丰富器(如 Serilog.Enrichers.Environment、Serilog.Enrichers.Thread 等),但不适用于我的自定义丰富器。这是相关代码:
public class ClassNameEnricher: ILogEventEnricher
{
private string GetClassName()
{
StackTrace trace = new StackTrace();
bool foundFrame = false;
int currentFrame = 0;
while (!foundFrame)
{
if (trace.GetFrame(currentFrame).GetMethod().ReflectedType.FullName == typeof(Logger).FullName)
{
foundFrame = true;
}
currentFrame++;
}
return trace.GetFrame(currentFrame).GetMethod().ReflectedType.FullName;
}
public virtual void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
LogEventProperty className = propertyFactory.CreateProperty("ClassName", GetClassName());
logEvent.AddPropertyIfAbsent(className);
}
}
public static class LoggerEnrichmentConfigurationExtensions
{
public static LoggerConfiguration WithClassName(this LoggerEnrichmentConfiguration enrich)
{
return enrich.With<ClassNameEnricher>();
}
} …Run Code Online (Sandbox Code Playgroud) 当我想使用 CustomSerilogRequestLogging作为中间件时,出现以下异常:
System.InvalidOperationException:尝试激活“Serilog.AspNetCore.RequestLoggingMiddleware”时无法解析类型“Serilog.Extensions.Hosting.DiagnosticContext”的服务。
我在外部库中的自定义 SerilogRequestLogging:
public static IApplicationBuilder UseCustomSerilogRequestLogging(this IApplicationBuilder app)
{
return app.UseSerilogRequestLogging(options =>
{
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
diagnosticContext.Set("RequestMethod", httpContext.Request.Method);
diagnosticContext.Set("RequestProtocol", httpContext.Request.Protocol);
diagnosticContext.Set("RequestPath", httpContext.Request.Path);
diagnosticContext.Set("RequestRemoteAddress", httpContext.Connection.RemoteIpAddress);
};
});
}
Run Code Online (Sandbox Code Playgroud)
然后我将它作为中间件添加到配置方法中,如下所示:
app.UseCustomSerilogRequestLogging();
Run Code Online (Sandbox Code Playgroud)
在程序.cs中:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseSerilog((provider, context, loggerConfig) =>
{
loggerConfig.Configure(provider, Configuration);
});
webBuilder.UseStartup<Startup>();
});
Run Code Online (Sandbox Code Playgroud)
外部库的扩展方法:
public static void Configure(this LoggerConfiguration loggerConfig,
IServiceProvider provider, IConfiguration config)
{
var sqlserverConnectionString = config["ConnectionStrings:S1"];
var sqlserverLogTable …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 ASP.Net Core 应用程序中使用 Serilog,但无法让它工作。一旦我在 Program.cs 中添加 .UseSerilog(),通常进入控制台屏幕的消息就会消失,并且不会创建任何日志文件。以下是我启用 Serilog 的方法:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
Run Code Online (Sandbox Code Playgroud)
这是我的应用程序设置:
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Grpc": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
Run Code Online (Sandbox Code Playgroud)
据我所知,默认情况下,日志文件似乎会被写入 VS.net 项目下的“logs”文件夹中(至少从我查看的示例来看是这样)。我想念什么?
我设置了一个 .Net 6 Core Minimal API,以使用 SeriLog 登录到 MS SQL Server。在我的类库中,仅当我修改类库中的构造函数时,我才能够使用 SeriLog 进行日志记录。我试图避免修改类库类或方法的构造函数。
根据我使用控制台应用程序的经验,如果我在主 Program.cs 中设置 SeriLog,那么我可以在类库中的任何类中使用日志记录,而无需将记录器传递给构造函数。因此,我可以在类库中的任何位置使用 Log.Information("my message") 并且它可以工作。我试图在 .Net 6 最小 API 项目中使用我的 Program.cs 实现相同的目标。
我觉得通过查看有关该主题的其他问题应该可以做到。特别是这个,其中的答案指出:
您无需在类库中执行任何操作。只有主应用程序具有组合根(应用程序生命周期中可以设置对象图的最早点)。
因此,根据上面的内容,在我的 API Program.CS 中,我有以下代码(我已在注释中指出了哪些有效,哪些无效):
//Configure SeriLog
builder.Logging.ClearProviders();
var appSettings = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var logDB =
builder.Configuration.GetSection("ConnectionStrings:Default").Value;
var sinkOpts = new MSSqlServerSinkOptions { TableName = "Logs" };
var columnOptions = new ColumnOptions();
var logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft",
Serilog.Events.LogEventLevel.Information)
.WriteTo.MSSqlServer(
connectionString: logDB,
sinkOptions: sinkOpts,
columnOptions: columnOptions,
appConfiguration: …Run Code Online (Sandbox Code Playgroud) 我有以下代码.
Serilog.ILogger logger = Serilog.Log.Logger;
logger = new LoggerConfiguration()
.WriteTo.Sink(new FileSink(@"c:\temp\mylogs.txt", new JsonFormatter(), null)).MinimumLevel.Debug()
.CreateLogger();
var newType = new MyType() { Game = "Poker", HasValue = false, Name = "Dave", TimeOfEntry = DateTime.Now.AddDays(-1) };
logger.Debug("This is the new type {NewType} generated at {Time}", newType, DateTime.Now);
Run Code Online (Sandbox Code Playgroud)
日志文件显示如下
{"Timestamp":"2015-02-11T00:53:51.8501574-05:00","Level":"Debug","MessageTemplate":"This is the new type {NewType} generated at {Time}","Properties":{"NewType":"ConsoleTestApp.MyType","Time":"2015-02-11T00:53:51.8491563-05:00"}}
Run Code Online (Sandbox Code Playgroud)
在日志文件输出中没有意义的部分是这样的:
{"NewType":"ConsoleTestApp.MyType", ...
Run Code Online (Sandbox Code Playgroud)
我期待这样的事情.
{"NewType": {Game = "Poker", HasValue = false, Name = "Dave", ...
Run Code Online (Sandbox Code Playgroud)
我做错什么了吗?
I have written a logging framework that uses Log4Net, Nlog and Serilog interchangeably. Every call to the logger, fires an event before the log entry is written. This optionally pushes entries via SignalR to connected web clients.
在添加serilog之前,我使用string.Format获取格式化的文本。如今,巨大的破坏带来了巨大的责任。string.Format显然不喜欢字符串中的{@ 0}或{data}。
// log the event before engaging with the logger
LogEventBus.Handle(LogLevels.Info, DateTime.Now, msg, args);
if (DiagnosticLevel < level)
return;
_logger.Info(msg, args);
Run Code Online (Sandbox Code Playgroud)
有什么方法可以直接以字符串形式获取serilog生成的输出?
我开始写一个内存接收器,但是它脱离了基于集中事件的日志记录,并且完全脱离了我已经实现的其他库。
有什么建议么?
如果我有以下课程
public class Customer
{
public string Name;
}
Run Code Online (Sandbox Code Playgroud)
然后在Serilog中有以下log命令
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.Seq("http://localhost:5341")
.CreateLogger();
var item = new Customer();
item.Name = "John";
Serilog.Log.Information("Customer {@item}", item);
Run Code Online (Sandbox Code Playgroud)
日志仅在Seq中显示为
Customer {}
Run Code Online (Sandbox Code Playgroud)
如果我将“名称”字段更改为一个属性,则可以使用,但我目前不希望这样做。有什么办法解决吗?
我编写了以下行来在C#/ WPF应用程序中创建我的记录器,但Debug消息不会显示在日志中.我错过了什么?我使用的是serilog.sinks.file版本4.0.0.发布版本生成信息级事件,但调试版本不会生成调试消息.我已确认已定义DEBUG符号,并且我已经调试以确认该级别实际上已设置为调试.
LogEventLevel level = LogEventLevel.Information;
#if DEBUG
level = LogEventLevel.Debug;
#endif
UsageLogger = new LoggerConfiguration()
.Enrich.With(new ThreadIdEnricher())
.WriteTo.File("UsageLogging.txt", restrictedToMinimumLevel: level, outputTemplate: LogTemplate, rollingInterval: RollingInterval.Day)
.Enrich.With(new ThreadIdEnricher())
.WriteTo.Console(restrictedToMinimumLevel: level, outputTemplate: LogTemplate)
.Enrich.With(new ThreadIdEnricher())
.CreateLogger();
}
Run Code Online (Sandbox Code Playgroud) 我在.Net项目中使用Serilog和Seq。我的主要目标是记录一些特定事件。我想拥有自己的日志事件级别(例如“警告”,“详细”,“信息” ...)。但是我真的不知道是否有可能拥有我的自定义日志级别:
private static readonly ILogger Logger = Log.ForContext<MyController>();
.
.
.
Logger.MyCustomLogLevel(....);
Run Code Online (Sandbox Code Playgroud)
可能吗?先感谢您
我正在尝试使用Serilog.Settings.Configuration预发布的NuGet包从appsettings.json加载我的Serilog配置。但是,当我使用Configuration.GetSection加载它时,该值继续返回为null。
这是我的Program.cs文件中的内容:
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(
(hostingContext, loggingBuilder) =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddSerilog(
new LoggerConfiguration()
.ReadFrom.ConfigurationSection(hostingContext.Configuration.GetSection("Serilog"))
.CreateLogger()
);
}
);
Run Code Online (Sandbox Code Playgroud)
这是我的appsettings.json文件中的内容:
{
"Serilog": {
"Using": [ "Serilog.Sinks.MSSqlServer" ],
"MinimumLevel": {
"Default": "Verbose",
"Override": {
"Microsoft": "Verbose",
"System": "Verbose",
"Microsoft.AspNetCore.Authentication": "Verbose"
}
},
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "*my_connectionString*",
"tableName": "ErrorLog"
}
}
]
}}
Run Code Online (Sandbox Code Playgroud)
NuGet软件包已安装: