programmerj
programmerj

Reputation: 1684

Using appSettings to configure a custom Serilog sink

I created a new Serilog custom sink and am trying to configure it via appSettings.

The custom sink is named 'DiagnosticsBroadcaster'. Its LoggerSinkConfiguration extension is:

public static LoggerConfiguration DiagnosticsBroadcaster(
        this LoggerSinkConfiguration loggerConfiguration,
        string defaultLoggerName = "serilog",
        LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
        IFormatProvider formatProvider = null)
    {
        if (loggerConfiguration == null)
        {
            throw new ArgumentNullException("loggerConfiguration");
        }

        if (defaultLoggerName == null)
        {
            throw new ArgumentNullException("defaultLoggerName");
        }

        return loggerConfiguration.Sink(new DiagnosticsBroadcaster(defaultLoggerName,     formatProvider), restrictedToMinimumLevel);
    } 

The DiagnosticsBroadcast sink class is:

public class DiagnosticsBroadcaster : ILogEventSink, IDisposable
{
    private OMMHttpClient _clientApp = null;
    private readonly string _defaultLoggerName = string.Empty;
    private readonly IFormatProvider _formatProvider = null;
    private readonly object _syncRoot = new object();
    private bool _isDisposed = false;

    //----------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------       
    public DiagnosticsBroadcaster(string defaultLoggerName, IFormatProvider formatProvider = null)
    {
        if (string.IsNullOrEmpty(defaultLoggerName))
        {
            throw new ArgumentException("defaultLoggerName");
        }

        _defaultLoggerName = defaultLoggerName;
        _formatProvider = formatProvider;

        string ommDispatcherUrl = ConfigurationManager.AppSettings["OMMDispatcherUrl"];

        _clientApp = new OMMHttpClient(ommDispatcherUrl, "api/omm/diag/app");            
    }

    //----------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------
    public void Emit(Serilog.Events.LogEvent logEvent)
    {
        var loggerName = _defaultLoggerName;

        string message;

        lock (_syncRoot)
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException("The OMMJHttpClient has been disposed.");
            }

            if (logEvent.Exception != null)
            {
                message = string.Format("{0} -- EXCEPTION: {1}", logEvent.RenderMessage(_formatProvider), logEvent.Exception.Message);
            }
            else
            {
                message = logEvent.RenderMessage(_formatProvider);
            }

            Task.Factory.StartNew(async () =>
            {
                try
                {
                    HttpResponseMessage response = await _clientApp.Post<string>(message);

                    if (!response.IsSuccessStatusCode)
                    {
                        Log.Warning("Error sending diagnostic message [APP] - {0} - {1}", response.StatusCode, response.ReasonPhrase);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warning("Error sending diagnostic message [APP]  - {0}", ex.Message);
                }
            });
        }
    }

    //----------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------  
    public void Dispose()
    {
        lock (_syncRoot)
        {
            if (_clientApp != null)
            {
                _clientApp.Dispose();
                _isDisposed = true;
            }
        }
    }
}

This custom sink works if I configure it as follows:

Log.Logger = new LoggerConfiguration()
                          .ReadAppSettings()
                          .WriteTo.DiagnosticsBroadcaster(restrictedToMinimumLevel: LogEventLevel.Information)                              
                          .CreateLogger();

But its methods are never called if I attempt to configure it via appSettings:

<add key="serilog:write-to:DiagnosticsBroadcaster.restrictedToMinimumLevel" value="Information" />

Any suggestions on how I can configure DiagnosticsBroadcaster via appSettings?

Thanks.

Upvotes: 3

Views: 5388

Answers (1)

Nicholas Blumhardt
Nicholas Blumhardt

Reputation: 31832

I think that you're most likely in need of a serilog:using directive for the assembly that contains the new sink:

<add key="serilog:using" value="YourCompany.YourAssembly" />

If you need to specify this for more than one additional sink, make the keys distinct by appending a short name:

<add key="serilog:using:Diag" value="YourCompany.YourAssembly" />

(It doesn't matter what the short name is, only that it is unique among app settings keys.

Upvotes: 3

Related Questions