static SerilogLoggerProvider CreateProvider(
            string serverUrl,
            string apiKey,
            LogLevel minimumLevel,
            IDictionary <string, LogLevel> levelOverrides)
        {
            var levelSwitch = new LoggingLevelSwitch(minimumLevel);

            var sink = new SeqSink(
                serverUrl,
                apiKey,
                1000,
                TimeSpan.FromSeconds(2),
                256 * 1024,
                levelSwitch,
                null);

            LevelOverrideMap overrideMap = null;

            if (levelOverrides != null && levelOverrides.Count != 0)
            {
                var overrides = new Dictionary <string, LoggingLevelSwitch>();
                foreach (var levelOverride in levelOverrides)
                {
                    overrides.Add(levelOverride.Key, new LoggingLevelSwitch(levelOverride.Value));
                }

                overrideMap = new LevelOverrideMap(overrides, levelSwitch);
            }

            var logger   = new Logger(levelSwitch, sink, sink.Dispose, overrideMap);
            var provider = new SerilogLoggerProvider(logger);

            return(provider);
        }
Exemplo n.º 2
0
        public void OverrideScenarios(string context, bool overrideExpected, LogEventLevel expected)
        {
            var overrides = new Dictionary <string, LoggingLevelSwitch>
            {
                ["MyApp"] = new LoggingLevelSwitch(LogEventLevel.Debug),
                ["MyApp.Api.Controllers"] = new LoggingLevelSwitch(LogEventLevel.Information),
                ["MyApp.Api.Controllers.HomeController"] = new LoggingLevelSwitch(LogEventLevel.Warning),
                ["MyApp.Api"] = new LoggingLevelSwitch(LogEventLevel.Error)
            };

            var lom = new LevelOverrideMap(overrides, LogEventLevel.Fatal, null);

            LoggingLevelSwitch overriddenSwitch;
            LogEventLevel      overriddenLevel;

            lom.GetEffectiveLevel(context, out overriddenLevel, out overriddenSwitch);

            if (overrideExpected)
            {
                Assert.NotNull(overriddenSwitch);
                Assert.Equal(expected, overriddenSwitch.MinimumLevel);
                Assert.Equal(LevelAlias.Minimum, overriddenLevel);
            }
            else
            {
                Assert.Equal(LogEventLevel.Fatal, overriddenLevel);
                Assert.Null(overriddenSwitch);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Create a logger using the configured sinks, enrichers and minimum level.
        /// </summary>
        /// <returns>The logger.</returns>
        /// <remarks>To free resources held by sinks ahead of program shutdown,
        /// the returned logger may be cast to <see cref="IDisposable"/> and
        /// disposed.</remarks>
        public Logger CreateLogger()
        {
            if (_loggerCreated)
            {
                throw new InvalidOperationException("CreateLogger() was previously called and can only be called once.");
            }
            _loggerCreated = true;

            Action dispose = () =>
            {
                foreach (var disposable in _logEventSinks.OfType <IDisposable>())
                {
                    disposable.Dispose();
                }
            };

            ILogEventSink sink = new SafeAggregateSink(_logEventSinks);

            if (_filters.Any())
            {
                sink = new FilteringSink(sink, _filters);
            }

            var converter = new PropertyValueConverter(_maximumDestructuringDepth, _additionalScalarTypes, _additionalDestructuringPolicies);
            var processor = new MessageTemplateProcessor(converter);

            ILogEventEnricher enricher;

            switch (_enrichers.Count)
            {
            case 0:
                // Should be a rare case, so no problem making that extra interface dispatch.
                enricher = new EmptyEnricher();
                break;

            case 1:
                enricher = _enrichers[0];
                break;

            default:
                enricher = new SafeAggregateEnricher(_enrichers);
                break;
            }

            LevelOverrideMap overrideMap = null;

            if (_overrides.Count != 0)
            {
                overrideMap = new LevelOverrideMap(_overrides, _minimumLevel, _levelSwitch);
            }

            return(_levelSwitch == null ?
                   new Logger(processor, _minimumLevel, sink, enricher, dispose, overrideMap) :
                   new Logger(processor, _levelSwitch, sink, enricher, dispose, overrideMap));
        }
        public SourceContextMatchBenchmark()
        {
            _contexts = new[]
            {
                "Serilog",
                "MyApp",
                "MyAppSomething",
                "MyOtherApp",
                "MyApp.Something",
                "MyApp.Api.Models.Person",
                "MyApp.Api.Controllers.AboutController",
                "MyApp.Api.Controllers.HomeController",
                "Api.Controllers.HomeController"
            };

            var overrides = new Dictionary <string, LoggingLevelSwitch>
            {
                ["MyApp"] = new LoggingLevelSwitch(LogEventLevel.Debug),
                ["MyApp.Api.Controllers"] = new LoggingLevelSwitch(LogEventLevel.Information),
                ["MyApp.Api.Controllers.HomeController"] = new LoggingLevelSwitch(LogEventLevel.Warning),
                ["MyApp.Api"] = new LoggingLevelSwitch(LogEventLevel.Error)
            };

            _levelOverrideMap = new LevelOverrideMap(overrides, LogEventLevel.Fatal, null);

            var loggerConfiguration = new LoggerConfiguration().MinimumLevel.Fatal();

            foreach (var @override in overrides)
            {
                loggerConfiguration = loggerConfiguration.MinimumLevel.Override(@override.Key, @override.Value);

                foreach (var ctx in _contexts)
                {
                    _loggersWithFilters.Add(
                        new LoggerConfiguration().MinimumLevel.Verbose()
                        .Filter.ByIncludingOnly(Matching.FromSource(@override.Key))
                        .WriteTo.Sink <NullSink>()
                        .CreateLogger()
                        .ForContext(Constants.SourceContextPropertyName, ctx));
                }
            }

            _loggerWithOverrides = loggerConfiguration.WriteTo.Sink <NullSink>().CreateLogger();
        }
        /// <summary>
        /// Adds a Seq logger configured from the supplied configuration section.
        /// </summary>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="serverUrl"></param>
        /// <param name="apiKey">A Seq API key to authenticate or tag messages from the logger.</param>
        /// <param name="minimumLevel">The level below which events will be suppressed (the default is <see cref="LogLevel.Information"/>).</param>
        /// <param name="levelOverrides">A dictionary mapping logger name prefixes to minimum logging levels.</param>
        /// <returns>A logger factory to allow further configuration.</returns>
        public static ILoggerFactory AddSeq(
            this ILoggerFactory loggerFactory,
            string serverUrl,
            string apiKey         = null,
            LogLevel minimumLevel = LogLevel.Information,
            IDictionary <string, LogLevel> levelOverrides = null)
        {
            var levelSwitch = new LoggingLevelSwitch(minimumLevel);

            var sink = new SeqSink(
                serverUrl,
                apiKey,
                1000,
                TimeSpan.FromSeconds(2),
                256 * 1024,
                levelSwitch,
                null);

            LevelOverrideMap overrideMap = null;

            if (levelOverrides != null && levelOverrides.Count != 0)
            {
                var overrides = new Dictionary <string, LoggingLevelSwitch>();
                foreach (var levelOverride in levelOverrides)
                {
                    overrides.Add(levelOverride.Key, new LoggingLevelSwitch(levelOverride.Value));
                }

                overrideMap = new LevelOverrideMap(overrides, levelSwitch);
            }

            var logger = new Logger(levelSwitch, sink, new LogContextEnricher(), sink.Dispose, overrideMap);

            loggerFactory.AddProvider(new SerilogLoggerProvider(logger));

            return(loggerFactory);
        }
        /// <summary>
        /// Create a logger using the configured sinks, enrichers and minimum level.
        /// </summary>
        /// <returns>The logger.</returns>
        /// <remarks>To free resources held by sinks ahead of program shutdown,
        /// the returned logger may be cast to <see cref="IDisposable"/> and
        /// disposed.</remarks>
        /// <exception cref="InvalidOperationException">When the logger is already created</exception>
        public Logger CreateLogger()
        {
            if (_loggerCreated)
            {
                throw new InvalidOperationException("CreateLogger() was previously called and can only be called once.");
            }

            _loggerCreated = true;

            ILogEventSink sink = new SafeAggregateSink(_logEventSinks);

            var auditing = _auditSinks.Any();

            if (auditing)
            {
                sink = new AggregateSink(new[] { sink }.Concat(_auditSinks));
            }

            if (_filters.Any())
            {
                // A throwing filter could drop an auditable event, so exceptions in filters must be propagated
                // if auditing is used.
                sink = new FilteringSink(sink, _filters, auditing);
            }

            var converter = new PropertyValueConverter(
                _maximumDestructuringDepth,
                _maximumStringLength,
                _maximumCollectionCount,
                _additionalScalarTypes,
                _additionalDestructuringPolicies,
                auditing);
            var processor = new MessageTemplateProcessor(converter);

            ILogEventEnricher enricher;

            switch (_enrichers.Count)
            {
            case 0:
                // Should be a rare case, so no problem making that extra interface dispatch.
                enricher = new EmptyEnricher();
                break;

            case 1:
                enricher = _enrichers[0];
                break;

            default:
                // Enrichment failures are not considered blocking for auditing purposes.
                enricher = new SafeAggregateEnricher(_enrichers);
                break;
            }

            LevelOverrideMap overrideMap = null;

            if (_overrides.Count != 0)
            {
                overrideMap = new LevelOverrideMap(_overrides, _minimumLevel, _levelSwitch);
            }

            var disposableSinks = _logEventSinks.Concat(_auditSinks).OfType <IDisposable>().ToArray();

            void Dispose()
            {
                foreach (var disposable in disposableSinks)
                {
                    disposable.Dispose();
                }
            }

            return(_levelSwitch == null ?
                   new Logger(processor, _minimumLevel, sink, enricher, Dispose, overrideMap) :
                   new Logger(processor, _levelSwitch, sink, enricher, Dispose, overrideMap));
        }