Esempio n. 1
0
 public RestrictedSink(ILogEventSink sink, LoggingLevelSwitch levelSwitch)
 {
     if (sink == null) throw new ArgumentNullException(nameof(sink));
     if (levelSwitch == null) throw new ArgumentNullException(nameof(levelSwitch));
     _sink = sink;
     _levelSwitch = levelSwitch;
 }
Esempio n. 2
0
        private static LoggerConfiguration GetConfiguration()
        {
            string minimumLogLevel = DbConfig.GetMixERPParameter(AppUsers.GetCurrentUserDB(), "MinimumLogLevel");

            LoggingLevelSwitch levelSwitch = new LoggingLevelSwitch();

            LogEventLevel logLevel;

            Enum.TryParse(minimumLogLevel, out logLevel);

            levelSwitch.MinimumLevel = logLevel;

            return
                (new LoggerConfiguration().MinimumLevel.ControlledBy(levelSwitch)
                 .WriteTo.RollingFile(GetLogFileName()));
        }
        /// <summary>
        /// Writes log events to the browser console.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        /// The default is <code>"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"</code>.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <param name="jsRuntime">An instance of <see cref="IJSRuntime"/> to interact with the browser.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public static LoggerConfiguration BrowserConsole(
            this LoggerSinkConfiguration sinkConfiguration,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate          = DefaultConsoleOutputTemplate,
            IFormatProvider formatProvider = null,
            LoggingLevelSwitch levelSwitch = null,
            IJSRuntime jsRuntime           = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }
            var formatter = new OutputTemplateRenderer(outputTemplate, formatProvider);

            return(sinkConfiguration.Sink(new BrowserConsoleSink(jsRuntime, formatter), restrictedToMinimumLevel, levelSwitch));
        }
Esempio n. 4
0
 void SubscribeToLoggingLevelChanges(IConfigurationSection levelSection, LoggingLevelSwitch levelSwitch)
 {
     ChangeToken.OnChange(
         levelSection.GetReloadToken,
         () =>
     {
         if (Enum.TryParse(levelSection.Value, out LogEventLevel minimumLevel))
         {
             levelSwitch.MinimumLevel = minimumLevel;
         }
         else
         {
             SelfLog.WriteLine($"The value {levelSection.Value} is not a valid Serilog level.");
         }
     });
 }
 /// <summary>
 /// Write log events to the Azure Diagnostic Application Log/>.
 /// </summary>
 /// <param name="sinkConfiguration">Logger sink configuration.</param>
 /// <param name="restrictedToMinimumLevel">The minimum level for
 /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
 /// <param name="levelSwitch">A switch allowing the pass-through minimum level
 /// to be changed at runtime.</param>
 /// <param name="formatter">A custom formatter to apply to the output events. This can be used with
 /// e.g. <see cref="JsonFormatter"/> to produce JSON output. To customize the text layout only, use the
 /// overload that accepts an output template instead.</param>
 /// <returns>Configuration object allowing method chaining.</returns>
 public static LoggerConfiguration AzureApp(
     this LoggerSinkConfiguration sinkConfiguration,
     ITextFormatter formatter,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     LoggingLevelSwitch levelSwitch         = null)
 {
     if (sinkConfiguration == null)
     {
         throw new ArgumentNullException(nameof(sinkConfiguration));
     }
     if (formatter == null)
     {
         throw new ArgumentNullException(nameof(formatter));
     }
     return(sinkConfiguration.Sink(new AzureAppSink(formatter), restrictedToMinimumLevel, levelSwitch));
 }
Esempio n. 6
0
        public static ILogger GetLogging()
        {
            var outputTemplate = "{Timestamp:HH:mm:ss} [{Level}] [ProcessId:{ProcessId}] [ThreadId:{ThreadId}] {Message}{NewLine}{Exception}";
            var levelSwitch    = new LoggingLevelSwitch {
                MinimumLevel = LogEventLevel.Debug
            };

            var configuration = new LoggerConfiguration()
                                .MinimumLevel.ControlledBy(levelSwitch)
                                .Enrich.WithThreadId()
                                .Enrich.WithProcessId()
                                .WriteTo.Console(theme: SystemConsoleTheme.Literate, outputTemplate: outputTemplate)
                                .WriteTo.Trace(outputTemplate: outputTemplate);

            return(configuration.CreateLogger());
        }
Esempio n. 7
0
        private static (SerilogILogger serilogger, LoggingLevelSwitch levelSwitch) SetupSerilog(SerilogLevel level)
        {
            var levelSwitch = new LoggingLevelSwitch(level);

            var serilogger =
                new LoggerConfiguration()
                .MinimumLevel.ControlledBy(levelSwitch)
                .Enrich.With <AllCapsLevelEnricher>()
                .WriteTo.Console(
                    formatProvider: CustomFormatProviderSingleton,
                    outputTemplate: BuildConsoleTemplate(),
                    theme: ConsoleTheme.None)
                .CreateLogger();

            return(serilogger, levelSwitch);
        }
Esempio n. 8
0
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            Func <string, string> settingsResolver = (name) => Configuration[name];

            var loggingLevelSwitch = new LoggingLevelSwitch();

            Log.Logger = Infrastructure.Logging.ApplicationLogging.CreateLogger(settingsResolver, "docker-dotnetcore-webapi", loggingLevelSwitch, "./logs");
        }
 public MetabaseCLIBuilder(
     IEnumerable <EntityFactory> factories,
     IEnumerable <ICommandBuilder> commandBuilders,
     CollectionFactory collectionFactory,
     LoggingLevelSwitch loggingLevelSwitch,
     SessionCredentials sessionCredentials,
     ILoggerFactory loggerFactory
     )
 {
     Factories          = factories;
     CollectionFactory  = collectionFactory;
     LoggingLevelSwitch = loggingLevelSwitch;
     LoggerFactory      = loggerFactory;
     CommandBuilders    = commandBuilders;
     SessionCredentials = sessionCredentials;
 }
Esempio n. 10
0
 /// <summary>
 /// Initializes a new Serilog logger that writes to xunit's <paramref name="testOutputHelper"/>.
 /// </summary>
 /// <param name="testOutputHelper">The <see cref="ITestOutputHelper"/> that will be written to.</param>
 /// <param name="restrictedToMinimumLevel">The minimum level for
 /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
 /// <param name="outputTemplate">A message template describing the format used to write to the sink.
 /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param>
 /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
 /// <param name="levelSwitch">A switch allowing the pass-through minimum level to be changed at runtime.</param>
 /// <returns>The Serilog logger that logs to <paramref name="testOutputHelper"/>.</returns>
 /// <exception cref="ArgumentNullException">Thrown when <paramref name="testOutputHelper"/> is null.</exception>
 public static Logger CreateTestLogger(
     this ITestOutputHelper testOutputHelper,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     string outputTemplate = TestOutputLoggerConfigurationExtensions.DefaultConsoleOutputTemplate,
     IFormatProvider formatProvider = null,
     LoggingLevelSwitch levelSwitch = null)
 {
     return new LoggerConfiguration()
           .WriteTo.TestOutput(
                testOutputHelper,
                restrictedToMinimumLevel,
                outputTemplate,
                formatProvider,
                levelSwitch)
           .CreateLogger();
 }
        public void LevelSwitchesCanBeLookedUpByName()
        {
            var @switch          = new LoggingLevelSwitch(LogEventLevel.Verbose);
            var switchName       = "$theSwitch";
            var declaredSwitches = new Dictionary <string, LoggingLevelSwitch>()
            {
                { switchName, @switch }
            };

            var stringArgumentValue = new StringArgumentValue(() => switchName);

            var resolvedSwitch = stringArgumentValue.ConvertTo(typeof(LoggingLevelSwitch), declaredSwitches);

            Assert.IsType <LoggingLevelSwitch>(resolvedSwitch);
            Assert.Same(@switch, resolvedSwitch);
        }
Esempio n. 12
0
        public static LoggerConfiguration NUnitOutput(
            this LoggerSinkConfiguration sinkConfiguration,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            IFormatProvider formatProvider         = null,
            LoggingLevelSwitch levelSwitch         = null,
            string outputTemplate = DefaultOutputTemplate)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }

            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(sinkConfiguration.Sink(new NUnitSink(formatter), restrictedToMinimumLevel, levelSwitch));
        }
Esempio n. 13
0
        public ILogger CreateLogger(string categoryName)
        {
            var eventLevel  = GetLevel(categoryName);
            var levelSwitch = new LoggingLevelSwitch(eventLevel);

            _loggerSwitches.GetOrAdd(categoryName, levelSwitch);

            var serilogger = new Serilog.LoggerConfiguration()
                             .ReadFrom.Configuration(_subLoggerConfiguration)
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .WriteTo.Logger(_globalLogger)
                             .CreateLogger();
            var factory = new SerilogLoggerFactory(serilogger, true);

            return(_loggers.GetOrAdd(categoryName, factory.CreateLogger(categoryName)));
        }
Esempio n. 14
0
 public SonarrCommand(
     ILogger log,
     LoggingLevelSwitch loggingLevelSwitch,
     ILogJanitor logJanitor,
     ISettingsPersister settingsPersister,
     ISettingsProvider settingsProvider,
     IConfigurationLoader <SonarrConfiguration> configLoader,
     Func <IReleaseProfileUpdater> profileUpdaterFactory,
     Func <ISonarrQualityDefinitionUpdater> qualityUpdaterFactory)
     : base(log, loggingLevelSwitch, logJanitor, settingsPersister, settingsProvider)
 {
     _log                   = log;
     _configLoader          = configLoader;
     _profileUpdaterFactory = profileUpdaterFactory;
     _qualityUpdaterFactory = qualityUpdaterFactory;
 }
Esempio n. 15
0
        private LoggerConfiguration GetConfiguration()
        {
            string minimumLogLevel = ConfigurationHelper.GetMixERPParameter("MinimumLogLevel");

            LoggingLevelSwitch levelSwitch = new LoggingLevelSwitch();

            LogEventLevel logLevel;

            Enum.TryParse(minimumLogLevel, out logLevel);

            levelSwitch.MinimumLevel = logLevel;

            return
                (new LoggerConfiguration().MinimumLevel.ControlledBy(levelSwitch)
                 .WriteTo.RollingFile(this.GetLogFileName()));
        }
Esempio n. 16
0
        public Logger CreateLogger(Microsoft.Extensions.Configuration.IConfigurationRoot config,
                                   LoggingLevelSwitch levelSwitch,
                                   string version, string providerName)
        {
            var loggerConfiguration = new LoggerConfiguration()
                                      .ReadFrom.Configuration(config)
                                      .MinimumLevel.ControlledBy(levelSwitch)
                                      .Enrich.WithProperty("version", version)
                                      .Enrich.WithProperty("environment", $"{config[InfrastructureConfigurationKeys.EnvironmentTag]}")
                                      .Enrich.WithProperty("providerName", providerName)
                                      .WriteTo.Console(new JsonFormatter());

            var logger = loggerConfiguration.CreateLogger();

            return(logger);
        }
Esempio n. 17
0
        /// <summary>
        /// Write log events to a sub-logger, where further processing may occur. Events through
        /// the sub-logger will be constrained by filters and enriched by enrichers that are
        /// active in the parent. A sub-logger cannot be used to log at a more verbose level, but
        /// a less verbose level is possible.
        /// </summary>
        /// <param name="configureLogger">An action that configures the sub-logger.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public LoggerConfiguration Logger(
            Action <LoggerConfiguration> configureLogger,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            LoggingLevelSwitch levelSwitch         = null)
        {
            if (configureLogger == null)
            {
                throw new ArgumentNullException(nameof(configureLogger));
            }
            var lc = new LoggerConfiguration();

            _applyInheritedConfiguration(lc);

            configureLogger(lc);
            return(Sink(new SecondaryLoggerSink(lc.CreateLogger(), attemptDispose: true), restrictedToMinimumLevel, levelSwitch));
        }
Esempio n. 18
0
        void ApplyMinimumLevel(LoggerConfiguration loggerConfiguration)
        {
            var minimumLevelDirective = _section.GetSection("MinimumLevel");

            var defaultMinLevelDirective = minimumLevelDirective.Value != null ? minimumLevelDirective : minimumLevelDirective.GetSection("Default");

            if (defaultMinLevelDirective.Value != null)
            {
                ApplyMinimumLevel(defaultMinLevelDirective, (configuration, levelSwitch) => configuration.ControlledBy(levelSwitch));
            }

            var minLevelControlledByDirective = minimumLevelDirective.GetSection("ControlledBy");

            if (minLevelControlledByDirective.Value != null)
            {
                var globalMinimumLevelSwitch = _resolutionContext.LookUpSwitchByName(minLevelControlledByDirective.Value);
                // not calling ApplyMinimumLevel local function because here we have a reference to a LogLevelSwitch already
                loggerConfiguration.MinimumLevel.ControlledBy(globalMinimumLevelSwitch);
            }

            foreach (var overrideDirective in minimumLevelDirective.GetSection("Override").GetChildren())
            {
                var overridePrefix         = overrideDirective.Key;
                var overridenLevelOrSwitch = overrideDirective.Value;
                if (Enum.TryParse(overridenLevelOrSwitch, out LogEventLevel _))
                {
                    ApplyMinimumLevel(overrideDirective, (configuration, levelSwitch) => configuration.Override(overridePrefix, levelSwitch));
                }
                else
                {
                    var overrideSwitch = _resolutionContext.LookUpSwitchByName(overridenLevelOrSwitch);
                    // not calling ApplyMinimumLevel local function because here we have a reference to a LogLevelSwitch already
                    loggerConfiguration.MinimumLevel.Override(overridePrefix, overrideSwitch);
                }
            }

            void ApplyMinimumLevel(IConfigurationSection directive, Action <LoggerMinimumLevelConfiguration, LoggingLevelSwitch> applyConfigAction)
            {
                var minimumLevel = ParseLogEventLevel(directive.Value);

                var levelSwitch = new LoggingLevelSwitch(minimumLevel);

                applyConfigAction(loggerConfiguration.MinimumLevel, levelSwitch);

                SubscribeToLoggingLevelChanges(directive, levelSwitch);
            }
        }
        // ReSharper disable once UnusedMember.Global
        // ReSharper disable once InconsistentNaming
        public static LoggerConfiguration PostgreSQL(
            this LoggerSinkConfiguration sinkConfiguration,
            string connectionString,
            string tableName,
            IDictionary <string, ColumnWriterBase> columnOptions = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            TimeSpan?period = null,
            IFormatProvider formatProvider = null,
            int batchSizeLimit             = DefaultBatchSizeLimit,
            int queueLimit = DefaultQueueLimit,
            LoggingLevelSwitch levelSwitch = null,
            bool useCopy                       = true,
            string schemaName                  = "",
            bool needAutoCreateTable           = false,
            bool needAutoCreateSchema          = false,
            Action <Exception> failureCallback = null,
            IConfiguration appConfiguration    = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }

            if (appConfiguration != null)
            {
                connectionString =
                    MicrosoftExtensionsConnectionStringProvider.GetConnectionString(connectionString, appConfiguration);
            }

            period ??= DefaultPeriod;

            var optionsLocal = GetOptions(
                connectionString,
                tableName,
                columnOptions,
                period.Value,
                formatProvider,
                batchSizeLimit,
                queueLimit,
                useCopy,
                schemaName,
                needAutoCreateTable,
                needAutoCreateSchema,
                failureCallback);

            return(sinkConfiguration.Sink(new PostgreSqlSink(optionsLocal), restrictedToMinimumLevel, levelSwitch));
        }
        public DurableSeqSink(
            string serverUrl,
            string bufferBaseFilename,
            string apiKey,
            int batchPostingLimit,
            TimeSpan period,
            long?bufferSizeLimitBytes,
            long?eventBodyLimitBytes,
            LoggingLevelSwitch levelControlSwitch,
            HttpMessageHandler messageHandler,
            long?retainedInvalidPayloadsLimitBytes)
        {
            if (serverUrl == null)
            {
                throw new ArgumentNullException(nameof(serverUrl));
            }
            if (bufferBaseFilename == null)
            {
                throw new ArgumentNullException(nameof(bufferBaseFilename));
            }


            _shipper = new HttpLogShipper(
                serverUrl,
                bufferBaseFilename,
                apiKey,
                batchPostingLimit,
                period,
                eventBodyLimitBytes,
                levelControlSwitch,
                messageHandler,
                retainedInvalidPayloadsLimitBytes,
                bufferSizeLimitBytes);

            const long individualFileSizeLimitBytes = 100L * 1024 * 1024;

            _sink = new LoggerConfiguration()
                    .MinimumLevel.Verbose()
                    .WriteTo.File(new RawJsonFormatter(),
                                  bufferBaseFilename + "-.json",
                                  rollingInterval: RollingInterval.Day,
                                  fileSizeLimitBytes: individualFileSizeLimitBytes,
                                  rollOnFileSizeLimit: true,
                                  retainedFileCountLimit: null,
                                  encoding: Encoding.UTF8)
                    .CreateLogger();
        }
        private static void ConfigureServices(IServiceCollection services)
        {
            var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + Path.DirectorySeparatorChar;

            //create logging
            var levelSwitch         = new LoggingLevelSwitch(LogEventLevel.Information);
            var loggerConfiguration = new LoggerConfiguration()
                                      .MinimumLevel.ControlledBy(levelSwitch);

            var formatter = GetLogFormatter();

            if (formatter != null)
            {
                loggerConfiguration
                .WriteTo.Console(formatter)
                .WriteTo.File(formatter, $"{path}logs{Path.DirectorySeparatorChar}log-.txt", rollingInterval: RollingInterval.Day);
            }
            else
            {
                loggerConfiguration
                .WriteTo.Console()
                .WriteTo.File($"{path}logs{Path.DirectorySeparatorChar}log-.txt", rollingInterval: RollingInterval.Day);
            }

            Log.Logger = loggerConfiguration.CreateLogger();

            //load radius attributes dictionary
            var dictionaryPath = path + "content" + Path.DirectorySeparatorChar + "radius.dictionary";
            var dictionary     = new RadiusDictionary(dictionaryPath, Log.Logger);

            //init configuration
            var configuration = ServiceConfiguration.Load(dictionary, Log.Logger);

            SetLogLevel(configuration.LogLevel, levelSwitch);

            services.AddSingleton(Log.Logger);
            services.AddSingleton(configuration);

            services.AddMemoryCache();

            services.AddSingleton <IRadiusDictionary>(dictionary);
            services.AddSingleton <IRadiusPacketParser, RadiusPacketParser>();
            services.AddSingleton <CacheService>();
            services.AddSingleton <RadiusServer>();

            services.AddHostedService <ServerHost>();
        }
Esempio n. 22
0
        /// <summary>
        /// Adds a sink that writes log events to the Loggly.com webservice. Properties are being send as data and the level is used as category.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param>
        /// <param name="period">The time to wait between checking for event batches.</param>
        /// <param name="bufferBaseFilename">Path for a set of files that will be used to buffer events until they
        /// can be successfully transmitted across the network. Individual files will be created using the
        /// pattern <paramref name="bufferBaseFilename"/>-{Date}.json.</param>
        /// <param name="bufferFileSizeLimitBytes">The maximum size, in bytes, to which the buffer
        /// log file for a specific date will be allowed to grow. By default no limit will be applied.</param>
        /// <param name="eventBodyLimitBytes">The maximum size, in bytes, that the JSON representation of
        /// an event may take before it is dropped rather than being sent to the Loggly server. Specify null for no limit.
        /// The default is 1 MB.</param>
        /// <param name="controlLevelSwitch">If provided, the switch will be updated based on the Seq server's level setting
        /// for the corresponding API key. Passing the same key to MinimumLevel.ControlledBy() will make the whole pipeline
        /// dynamically controlled. Do not specify <paramref name="restrictedToMinimumLevel"/> with this setting.</param>
        /// <param name="retainedInvalidPayloadsLimitBytes">A soft limit for the number of bytes to use for storing failed requests.
        /// The limit is soft in that it can be exceeded by any single error payload, but in that case only that single error
        /// payload will be retained.</param>
        /// <param name="retainedFileCountLimit">number of files to retain for the buffer</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration Loggly(
            this LoggerSinkConfiguration loggerConfiguration,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit                  = LogglySink.DefaultBatchPostingLimit,
            TimeSpan?period                        = null,
            IFormatProvider formatProvider         = null,
            string bufferBaseFilename              = null,
            long?bufferFileSizeLimitBytes          = null,
            long?eventBodyLimitBytes               = 1024 * 1024,
            LoggingLevelSwitch controlLevelSwitch  = null,
            long?retainedInvalidPayloadsLimitBytes = null,
            int?retainedFileCountLimit             = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (bufferFileSizeLimitBytes.HasValue && bufferFileSizeLimitBytes < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bufferFileSizeLimitBytes), "Negative value provided; file size limit must be non-negative.");
            }

            var defaultedPeriod = period ?? LogglySink.DefaultPeriod;

            ILogEventSink sink;

            if (bufferBaseFilename == null)
            {
                sink = new LogglySink(formatProvider, batchPostingLimit, defaultedPeriod);
            }
            else
            {
                sink = new DurableLogglySink(
                    bufferBaseFilename,
                    batchPostingLimit,
                    defaultedPeriod,
                    bufferFileSizeLimitBytes,
                    eventBodyLimitBytes,
                    controlLevelSwitch,
                    retainedInvalidPayloadsLimitBytes,
                    retainedFileCountLimit,
                    formatProvider);
            }

            return(loggerConfiguration.Sink(sink, restrictedToMinimumLevel));
        }
        const int DefaultRetainedFileCountLimit   = 31; // A long month of logs


        /// <summary>
        /// Writes log events to <see cref="System.Console"/>, using color to differentiate
        /// between levels.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public static LoggerConfiguration ColoredConsole(
            this LoggerSinkConfiguration sinkConfiguration,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate          = DefaultConsoleOutputTemplate,
            IFormatProvider formatProvider = null,
            LoggingLevelSwitch levelSwitch = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }
            if (outputTemplate == null)
            {
                throw new ArgumentNullException(nameof(outputTemplate));
            }
            return(sinkConfiguration.Sink(new ColoredConsoleSink(outputTemplate, formatProvider), restrictedToMinimumLevel, levelSwitch));
        }
Esempio n. 24
0
        public static ILogger InitLogger(string serviceKeyName,
                                         LoggingLevelSwitch loggingLevelSwitch)
        {
            var loggerConfiguration = new LoggerConfiguration()
                                      .Enrich.FromLogContext()
                                      .Enrich.WithProperty("log_service_key", serviceKeyName)
                                      .Enrich.WithExceptionDetails()
                                      .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                                      .MinimumLevel.ControlledBy(loggingLevelSwitch)
                                      .WriteTo.LiterateConsole();

            var logger = loggerConfiguration.CreateLogger();

            Log.Logger = logger;

            return(logger);
        }
Esempio n. 25
0
 /// <summary>
 /// Provides configuration for RollbarSink.
 /// </summary>
 /// <param name="loggerConfiguration">The logger configuration.</param>
 /// <param name="rollbarAccessToken">The Rollbar access token.</param>
 /// <param name="rollbarEnvironment">The Rollbar environment.</param>
 /// <param name="restrictedToMinimumLevel">
 ///   The minimum level for events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.
 /// </param>
 /// <param name="levelSwitch">A switch allowing the pass-through minimum level to be changed at runtime.</param>
 /// <returns>LoggerConfiguration.</returns>
 public static LoggerConfiguration RollbarSink(
     this LoggerSinkConfiguration loggerConfiguration,
     string rollbarAccessToken,
     string rollbarEnvironment,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     LoggingLevelSwitch levelSwitch         = null
     )
 {
     return(RollbarSink(
                loggerConfiguration,
                rollbarAccessToken,
                rollbarEnvironment,
                null,
                null,
                restrictedToMinimumLevel,
                levelSwitch));
 }
Esempio n. 26
0
        /// <summary>
        /// Provides configuration for RollbarSink.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="rollbarAccessToken">The Rollbar access token.</param>
        /// <param name="rollbarEnvironment">The Rollbar environment.</param>
        /// <param name="rollbarBlockingLoggingTimeout">The Rollbar blocking logging timeout.</param>
        /// <param name="formatProvider">The format provider.</param>
        /// <param name="restrictedToMinimumLevel">
        ///   The minimum level for events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.
        /// </param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level to be changed at runtime.</param>
        /// <returns>LoggerConfiguration.</returns>
        public static LoggerConfiguration RollbarSink(
            this LoggerSinkConfiguration loggerConfiguration,
            string rollbarAccessToken,
            string rollbarEnvironment,
            TimeSpan?rollbarBlockingLoggingTimeout,
            IFormatProvider formatProvider,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            LoggingLevelSwitch levelSwitch         = null
            )
        {
            IRollbarConfig config = new RollbarConfig(rollbarAccessToken)
            {
                Environment = rollbarEnvironment,
            };

            return(loggerConfiguration.RollbarSink(config, rollbarBlockingLoggingTimeout, formatProvider, restrictedToMinimumLevel, levelSwitch));
        }
        /// <summary>
        /// Writes log events to an in-memory log sink.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public static LoggerConfiguration InMemory(
            this LoggerSinkConfiguration sinkConfiguration,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate          = DefaultOutputTemplate,
            LoggingLevelSwitch levelSwitch = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }
            if (outputTemplate == null)
            {
                throw new ArgumentNullException(nameof(outputTemplate));
            }

            return(sinkConfiguration.Sink(InMemorySink.Instance, restrictedToMinimumLevel, levelSwitch));
        }
Esempio n. 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Dalamud"/> class.
        /// </summary>
        /// <param name="info">DalamudStartInfo instance.</param>
        /// <param name="loggingLevelSwitch">LoggingLevelSwitch to control Serilog level.</param>
        /// <param name="finishSignal">Signal signalling shutdown.</param>
        /// <param name="configuration">The Dalamud configuration.</param>
        public Dalamud(DalamudStartInfo info, LoggingLevelSwitch loggingLevelSwitch, ManualResetEvent finishSignal, DalamudConfiguration configuration)
        {
#if DEBUG
            Instance = this;
#endif
            this.StartInfo      = info;
            this.LogLevelSwitch = loggingLevelSwitch;
            this.Configuration  = configuration;

            // this.baseDirectory = info.WorkingDirectory;

            this.unloadSignal = new ManualResetEvent(false);
            this.unloadSignal.Reset();

            this.finishUnloadSignal = finishSignal;
            this.finishUnloadSignal.Reset();
        }
        public static Logger Create(
            string appName,
            ConfigurationServiceBase sharedConfig,
            LoggerConfigPredicate configPredicate = null)
        {
            if (Svc.Logger != null)
            {
                throw new NotSupportedException();
            }

            var config      = LoadConfig(sharedConfig);
            var levelSwitch = new LoggingLevelSwitch(config.LogLevel);

            Log.Logger = CreateSerilog(appName, config, levelSwitch, configPredicate);

            return(new Logger(config, levelSwitch));
        }
Esempio n. 30
0
        private static LoggerConfiguration GetConfiguration()
        {
            string minimumLogLevel = ConfigurationManager.GetConfigurationValue("ParameterConfigFileLocation",
                                                                                "MinimumLogLevel");

            var levelSwitch = new LoggingLevelSwitch();

            LogEventLevel logLevel;

            Enum.TryParse(minimumLogLevel, out logLevel);

            levelSwitch.MinimumLevel = logLevel;

            return
                (new LoggerConfiguration().MinimumLevel.ControlledBy(levelSwitch)
                 .WriteTo.RollingFile(GetLogFileName()));
        }
        /// <summary>
        /// Writes log events to <see cref="T:System.Console" />.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="testOutputHelper">The test output helper.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch" /> is specified.</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        ///the default is <code>"[{Timestamp:HH:mm:ss} {Level:u3}] {Message}{NewLine}{Exception}"</code>.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        /// <exception cref="ArgumentNullException">sinkConfiguration</exception>
        public static LoggerConfiguration XUnit(this LoggerSinkConfiguration sinkConfiguration,
                                                ITestOutputHelper testOutputHelper,
                                                LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose,
                                                string outputTemplate          = DefaultOutputTemplate,
                                                IFormatProvider formatProvider = null,
                                                LoggingLevelSwitch levelSwitch = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }


            return(sinkConfiguration.Sink(
                       new XUnitLogEventSink(testOutputHelper, outputTemplate, formatProvider),
                       restrictedToMinimumLevel, levelSwitch));
        }