17

我正在尝试将OpenTracing.Contrib.NetCore与 Serilog 一起使用。我需要将我的自定义日志发送给 Jaeger。现在,它仅在我使用默认记录器工厂时才有效Microsoft.Extensions.Logging.ILoggerFactory

我的启动:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddSingleton<ITracer>(sp =>
    {
        var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
        string serviceName = sp.GetRequiredService<IHostingEnvironment>().ApplicationName;

        var samplerConfiguration = new Configuration.SamplerConfiguration(loggerFactory)
            .WithType(ConstSampler.Type)
            .WithParam(1);

        var senderConfiguration = new Configuration.SenderConfiguration(loggerFactory)
            .WithAgentHost("localhost")
            .WithAgentPort(6831);

        var reporterConfiguration = new Configuration.ReporterConfiguration(loggerFactory)
            .WithLogSpans(true)
            .WithSender(senderConfiguration);

        var tracer = (Tracer)new Configuration(serviceName, loggerFactory)
            .WithSampler(samplerConfiguration)
            .WithReporter(reporterConfiguration)
            .GetTracer();

        //GlobalTracer.Register(tracer);
        return tracer;
    });
    services.AddOpenTracing();
}

在控制器的某个地方:

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    private readonly ILogger<ValuesController> _logger;

    public ValuesController(ILogger<ValuesController> logger)
    {
        _logger = logger;
    }

    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        _logger.LogWarning("Get values by id: {valueId}", id);
        return "value";
    }
}

结果,我将能够在 Jaeger UI 中看到该日志 在此处输入图像描述

但是当我使用 Serilog 时,没有任何自定义日志。我已添加UseSerilog()WebHostBuilder, 以及我可以在控制台中看到但在 Jaeger 中看不到的所有自定义日志。github中有未解决的问题。您能否建议我如何将 Serilog 与 OpenTracing 一起使用?

4

2 回答 2

12

这是 Serilog 记录器工厂实现中的一个限制;特别是,Serilog 当前忽略添加的提供程序,并假设 Serilog 接收器将替换它们。

因此,解决方案是实现一种WriteTo.OpenTracing()将 Serilog 直接连接到的简单方法OpenTracing

public class OpenTracingSink : ILogEventSink
{
    private readonly ITracer _tracer;
    private readonly IFormatProvider _formatProvider;

    public OpenTracingSink(ITracer tracer, IFormatProvider formatProvider)
    {
        _tracer = tracer;
        _formatProvider = formatProvider;
    }

    public void Emit(LogEvent logEvent)
    {
        ISpan span = _tracer.ActiveSpan;

        if (span == null)
        {
            // Creating a new span for a log message seems brutal so we ignore messages if we can't attach it to an active span.
            return;
        }

        var fields = new Dictionary<string, object>
        {
            { "component", logEvent.Properties["SourceContext"] },
            { "level", logEvent.Level.ToString() }
        };

        fields[LogFields.Event] = "log";

        try
        {
            fields[LogFields.Message] = logEvent.RenderMessage(_formatProvider);
            fields["message.template"] = logEvent.MessageTemplate.Text;

            if (logEvent.Exception != null)
            {
                fields[LogFields.ErrorKind] = logEvent.Exception.GetType().FullName;
                fields[LogFields.ErrorObject] = logEvent.Exception;
            }

            if (logEvent.Properties != null)
            {
                foreach (var property in logEvent.Properties)
                {
                    fields[property.Key] = property.Value;
                }
            }
        }
        catch (Exception logException)
        {
            fields["mbv.common.logging.error"] = logException.ToString();
        }

        span.Log(fields);
    }
}

public static class OpenTracingSinkExtensions
{
    public static LoggerConfiguration OpenTracing(
              this LoggerSinkConfiguration loggerConfiguration,
              IFormatProvider formatProvider = null)
    {
        return loggerConfiguration.Sink(new OpenTracingSink(GlobalTracer.Instance, formatProvider));
    }
}
于 2019-05-20T19:55:44.260 回答
2

您必须告诉 Serilog 使用 writeToProviders 将日志条目传递给 ILoggerProvider:true

.UseSerilog(
    (hostingContext, services, loggerConfiguration) => /* snip! */,
    writeToProviders: true)

这只会转发使用 ILogger 编写的内容。写入 SeriLog Log 方法的东西似乎没有成功。

于 2021-05-15T18:40:11.737 回答