是否可以检查 Serilog 中是否已记录任何错误ILogger?
var log = new LoggerConfiguration().CreateLogger();
SomeAlgorithm(log);
// How can I check if an error was logged?
Run Code Online (Sandbox Code Playgroud) 我试图在日志上为一台机器上同时运行的每个进程提供唯一的名称。我尝试将 app.config 中的 pathFormat 设置为类似于
<add key="MyApp:serilog:write-to:RollingFile.pathFormat"
value="..\log\MyApp.{MachineName}-{ThreadId}-{Date}.log" />
Run Code Online (Sandbox Code Playgroud)
那行不通。
任何想法?我在文档中找不到任何内容。
能够从多个源写入输出将不需要为每个进程都记录日志。由于(目前)我坚持使用 1.5,因此我在配置滚动文件时提供了特定路径。
new LoggerConfiguration()
.ReadFrom.AppSettings(AppName)
.WriteTo.RollingFile(path)
Run Code Online (Sandbox Code Playgroud)
我只需要提供计算机名称和线程 ID 即可获取唯一的日志文件名。
我当前正在使用 Serilog,我希望能够将一个类传递给记录器并让它在输出到文本文件之前以自定义格式记录。有点类似于IFormatProvider。我也发现了ITextFormatter,但我不确定这是否是正确的实施方式。我想要一个定制水槽吗?
我知道我可以通过这种方式添加丰富器:
{
"Serilog": {
"Using": [
"Serilog",
"Serilog.Enrichers.Environment",
"Serilog.Enrichers.Process",
...
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithProcessId"
]
...
Run Code Online (Sandbox Code Playgroud)
我可以对房产 ( ApplicationName) 做同样的事情吗?
我正在开发一个 WPF 应用程序,可以成功地设置 serilog 并通过将它放在 App.xaml.cs 中来访问它的静态方法,
但是,我还想登录项目中各种引用的类库。
由于循环依赖,我无法从类库本身引用主应用程序,因此在这些类库中执行日志记录的最佳方法是什么?
public class LogManager : IMLogManager
{
#region Constructor
public LogManager()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.WriteTo.Console(LogEventLevel.Debug, OutputTemplate, theme: AnsiConsoleTheme.Code)
.WriteTo.Async(a => a.File("./log/log.log",
LogEventLevel.Debug,
OutputTemplate,
rollingInterval: RollingInterval.Day,
encoding: Encoding.UTF8,
buffered: true,
rollOnFileSizeLimit: true))
.CreateLogger();
}
#endregion
#region Private properties
/// <summary>
/// Template ghi log.
/// </summary>
public static string OutputTemplate =>
"[{Timestamp:dd-MM-yyyy HH:mm:ss.fff} {Level:u3}] source {SourceContext} ::: {Message:lj}{NewLine}{Exception}{NewLine}";
#endregion
#region Private methods
private static string FormatMessage(string message,
string memberName …Run Code Online (Sandbox Code Playgroud) 日志记录正在运行,但没有发布到我的本地 seq,我尝试添加 serilog 并使用 Serilog 但它没有登录到我的本地服务:相关问题
.csproj
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.Mvc" Version="5.2.7" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.0.1" />
<PackageReference Include="Serilog" Version="2.8.0" />
<PackageReference Include="Serilog.AspNetCore" Version="3.0.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="3.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="4.6.0" />
Run Code Online (Sandbox Code Playgroud)
程序
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(loggingBuilder => {
loggingBuilder.AddEventLog();
loggingBuilder.AddSerilog();
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
})
.UseSerilog();
Run Code Online (Sandbox Code Playgroud)
appSettings.json:
"Serilog": {
"LevelSwitches": { "$controlSwitch": "Verbose" },
"MinimumLevel": { …Run Code Online (Sandbox Code Playgroud) 我有一个ASP .NET Core应用程序,我正在尝试Serilog用一个属性来丰富记录器并将它传递给 throghout 方法调用。我曾经Serilog.Context丰富它无济于事,该属性不存在于日志中。
程序
Log.Logger = new LoggerConfiguration().Enrich.FromLogContext()
.WriteTo.File(logpath)
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
控制器
public class SomeController{
public ILogger logger=Log.ForContext<SomeController>();
private SomeService Service;
public SomeController(SomeService serv)
{
this.service=serv;
}
[HttpGet]
public async Task DoSomething()
{
string corellationId=Guid.NewGuid().ToString();
LogContext.PushProperty("id",corellationId);
service.Run();
}
}
Run Code Online (Sandbox Code Playgroud)
服务
class SomeService
{
private ILogger logger=Log.ForContext<SomeService>();
public void Run()
{
logger.Information("I AM NOT SEEING the ID from upstream !");
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,我希望日志SomeService的 id 提供给上游(控制器操作)。我想要的是:
"[id] [value]"+ "[SomeService log]"
Run Code Online (Sandbox Code Playgroud)
PS如果重要的话,服务是通过依赖注入注入的。
尝试使用 Mock 对信号器组件进行单元测试时遇到问题。这是问题发生的地方
_logger.LogInformation($"Registering a Station with id: {Id}" +
$" with status: {Status}" +
$"{(!string.IsNullOrEmpty(CommandId) ? $", with command: {CommandId}" : "")}",
LoggingConstants.Component.MessageHub,
LoggingConstants.Class.Workstation,
!string.IsNullOrEmpty(AppointmentId) ?
AppointmentId : LoggingConstants.NoAppointmentId,
LoggingConstants.NoConfirmationNumber);
Run Code Online (Sandbox Code Playgroud)
LogInformation 定义为
logger.ForContext("Component", (object) component, false).ForContext("Class", (object) @class,
false).ForContext("AppointmentId", (object) appointmentId, false).ForContext("ConfirmationNumber",
(object) confirmationNumber, false).Information(message);
Run Code Online (Sandbox Code Playgroud)
在 Xunit 单元测试类中,它被用作
public Mock<ILogger> MockLogger { get; set; }
MockLogger = new Mock<ILogger>();
Workstation = new Workstation(MockLogger.Object);
Run Code Online (Sandbox Code Playgroud)
当单元测试运行时,一旦它遇到 _logger.LogInformation() 消息,它就会抛出一个
"System.NullReferenceException : Object reference not set to an instance of an object.
at …Run Code Online (Sandbox Code Playgroud) 目前,我正在直接使用 azure 应用程序洞察进行日志记录,如此链接 使用最新版本的 Application Insight 和 .net 核心 API ,一切正常。
但是我现在需要借助 azure 应用程序洞察来使用 serilog 进行日志记录。甚至我也做了一些关于 serilog 的研发(https://github.com/serilog/serilog-sinks-applicationinsights)。但没有任何想法。您能否建议我如何使用 .Net core 3.0 实现这一目标
我希望在我的 Serilog 输出中使用格式化的 UTC 时间戳。我编写了一个自定义丰富器,从 C# 代码调用时可以正常工作。
public class UtcTimestampEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory pf)
{
logEvent.AddPropertyIfAbsent(pf.CreateProperty("UtcTimestamp", logEvent.Timestamp.UtcDateTime));
}
}
....
var loggerConfig = new LoggerConfiguration().MinimumLevel.Debug()
.Enrich.FromLogContext()
.Enrich.With(new UtcTimestampEnricher())
.Filter
.ByIncludingOnly( expr) // need this .Filter to ensure that
// Serilog.Filters.Expressions.dll gets loaded, else filters in config file get ignored
.WriteTo.Console(
outputTemplate: "[{UtcTimestamp:HH:mm:ss.fff} {Level:u3} {Subsystem}] {Message:lj}{NewLine}{Exception}",
restrictedToMinimumLevel: LogEventLevel.Information);
Log.Logger = loggerConfig.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
现在我希望在从我的自定义 json 配置文件配置记录器时使用 utcTimestamp 扩充器。
var jsonLogconfiguration = new ConfigurationBuilder()
.AddJsonFile(logconfigFname)
.Build();
Log.Logger = new …Run Code Online (Sandbox Code Playgroud) serilog ×10
c# ×4
asp.net-core ×2
.net ×1
azure ×1
logging ×1
mocking ×1
seq-logging ×1
signalr-hub ×1
xunit ×1