标签: serilog

是否可以检查 Serilog 中是否已将任何错误记录到“ILogger”?

是否可以检查 Serilog 中是否已记录任何错误ILogger

var log = new LoggerConfiguration().CreateLogger();

SomeAlgorithm(log);

// How can I check if an error was logged?
Run Code Online (Sandbox Code Playgroud)

serilog

2
推荐指数
1
解决办法
733
查看次数

如何通过进程ID设置滚动文件名唯一

我试图在日志上为一台机器上同时运行的每个进程提供唯一的名称。我尝试将 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 即可获取唯一的日志文件名。

c# serilog

2
推荐指数
1
解决办法
3440
查看次数

类的自定义格式

我当前正在使用 Serilog,我希望能够将一个类传递给记录器并让它在输出到文本文件之前以自定义格式记录。有点类似于IFormatProvider。我也发现了ITextFormatter,但我不确定这是否是正确的实施方式。我想要一个定制水槽吗?

serilog

2
推荐指数
1
解决办法
1121
查看次数

有没有办法通过配置属性来丰富日志?

我知道我可以通过这种方式添加丰富器:

{
  "Serilog": {
    "Using": [
      "Serilog",
      "Serilog.Enrichers.Environment",
      "Serilog.Enrichers.Process",
      ...
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithProcessId"
    ]
...
Run Code Online (Sandbox Code Playgroud)

我可以对房产 ( ApplicationName) 做同样的事情吗?

configuration serilog

2
推荐指数
1
解决办法
3030
查看次数

如何在引用的类库中使用 serilog 并与 CallerMember、CallerFilePath(不是 asp.net 核心)一起使用

我正在开发一个 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)

.net c# serilog

2
推荐指数
1
解决办法
3180
查看次数

如何为 .NET Core 3.0 Worker Service 设置 serilog SEQ

日志记录正在运行,但没有发布到我的本地 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)

serilog .net-core-3.0 seq-logging

2
推荐指数
1
解决办法
4753
查看次数

从上下文中丰富 Serilog 不起作用

我有一个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如果重要的话,服务是通过依赖注入注入的。

logging serilog asp.net-core

2
推荐指数
1
解决办法
5852
查看次数

Serilog ILogger.ForContext 在 XUnit Mock 中抛出 NullReferenceException

尝试使用 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)

mocking xunit signalr-hub serilog asp.net-core-signalr

2
推荐指数
1
解决办法
549
查看次数

将 serilog 与 azure 应用程序洞察和 .Net 核心结合使用

目前,我正在直接使用 azure 应用程序洞察进行日志记录,如此链接 使用最新版本的 Application Insight 和 .net 核心 API ,一切正常。

但是我现在需要借助 azure 应用程序洞察来使用 serilog 进行日志记录。甚至我也做了一些关于 serilog 的研发(https://github.com/serilog/serilog-sinks-applicationinsights)。但没有任何想法。您能否建议我如何使用 .Net core 3.0 实现这一目标

c# azure serilog azure-application-insights asp.net-core

2
推荐指数
1
解决办法
5578
查看次数

如何让 Serilog 使用来自 json 配置文件的自定义丰富器

我希望在我的 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)

c# configuration serilog

2
推荐指数
1
解决办法
2521
查看次数