Esempio n. 1
3
        public void WriteLog(ICorrelation correlation, LogEventLevel eventLevel, Exception exception, string formatMessage, params object[] args)
        {
            if (log == null)
            {
                log = loggerRepository.GetLogger(sourceType);
            }

            if (eventLevel == LogEventLevel.Verbose && !log.IsDebugEnabled)
            {
                return;
            }

            if (args != null && args.Length != 0)
            {
                formatMessage = string.Format(formatMessage, args);
            }

            log4net.Core.ILogger logger = log.Logger;

            LoggingEvent logEvent = new LoggingEvent(sourceType, logger.Repository, logger.Name, MapEventLevel(eventLevel), formatMessage, exception);

            if (correlation != null)
            {
                logEvent.Properties["CallerId"] = correlation.CallerId;
                logEvent.Properties["CorrelationId"] = correlation.CorrelationId;
            }

            logger.Log(logEvent);
        }
        /// <summary>
        /// Adds a sink that writes log events as documents to a MongoDb database.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="databaseUrl">The URL of a created MongoDB collection that log events will be written to.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="cappedMaxSizeMb">Max total size in megabytes of the created capped collection. (Default: 50mb)</param>
        /// <param name="cappedMaxDocuments">Max number of documents of the created capped collection.</param>
        /// <param name="collectionName">Name of the collection. Default is "log".</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="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration MongoDBCapped(
            this LoggerSinkConfiguration loggerConfiguration,
            string databaseUrl,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            long cappedMaxSizeMb = 50,
            long? cappedMaxDocuments = null,
            string collectionName = null,
            int batchPostingLimit = MongoDBSink.DefaultBatchPostingLimit,
            TimeSpan? period = null,
            IFormatProvider formatProvider = null)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
            if (databaseUrl == null) throw new ArgumentNullException("databaseUrl");

            var optionsBuilder = CollectionOptions.SetCapped(true).SetMaxSize(cappedMaxSizeMb * 1024 * 1024);

            if (cappedMaxDocuments.HasValue)
            {
                optionsBuilder = optionsBuilder.SetMaxDocuments(cappedMaxDocuments.Value);
            }

            var defaultedPeriod = period ?? MongoDBSink.DefaultPeriod;
            return loggerConfiguration.Sink(
                new MongoDBSink(
                    databaseUrl,
                    batchPostingLimit,
                    defaultedPeriod,
                    formatProvider,
                    collectionName ?? MongoDBSink.DefaultCollectionName,
                    optionsBuilder),
                restrictedToMinimumLevel);
        }
 public static LoggerConfiguration Log4Net(
     this LoggerSinkConfiguration loggerConfiguration,
     LogEventLevel restrictedToMinimumLevel,
     IFormatProvider formatProvider)
 {
     return loggerConfiguration.Log4Net(null, restrictedToMinimumLevel, formatProvider);
 }
Esempio n. 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OperationContext" /> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="identifier">The identifier used for the operation. If not specified, a random guid will be used.</param>
        /// <param name="description">A description for the operation.</param>
        /// <param name="level">The level used to write the operation details to the logger. By default this is the information level.</param>
        /// <param name="warnIfExceeds">Specifies a limit, if it takes more than this limit, the level will be set to warning. By default this is not used.</param>
        /// <param name="autoSucceedOnExit">Specifies whether or not the operation should be marked with an outcome of <see cref="OperationOutcome.Success"/> if it completes without exception.</param>
        /// <param name="autoFailOnException">Specifies whether or not the operation should be marked with an outcome of <see cref="OperationOutcome.Fail"/> if an exception is detected.</param>
        /// <param name="propertyBag">A colletion of additional properties to associate with the current operation. This is typically an anonymous type.</param>
        internal OperationContext(ILogger logger,
                                  LogEventLevel level,
                                  TimeSpan? warnIfExceeds,
                                  object identifier,
                                  string description,
                                  bool autoSucceedOnExit,
                                  bool autoFailOnException,
                                  object propertyBag)
        {
            _logger = logger;
            _level = level;
            _warnIfExceeds = warnIfExceeds;
            _identifier = identifier;
            _description = description;
            _autoSucceedOnExit = autoSucceedOnExit;
            _autoFailOnException = autoFailOnException;

            _operationContextBookmark = OperationLogContext.PushOperationId(identifier);

            if (propertyBag != null)
            {
                // Save the first contextual property that we set. We then dispose of this bookmark, reverting the stack to what it was previously
                _contextualPropertiesBookmark = PushProperties(propertyBag);
            }

            _logger.Write(_level, BeginOperationMessage, _identifier, _description);

            _sw = Stopwatch.StartNew();
        }
        public static LoggerConfiguration NewRelic(
            this LoggerSinkConfiguration loggerSinkConfiguration,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit = NewRelicSink.DefaultBatchPostingLimit,
            TimeSpan? period = null,
            string applicationName = null,
            string bufferBaseFilename = null,
            long? bufferFileSizeLimitBytes = null)
        {
            if (loggerSinkConfiguration == null) throw new ArgumentNullException("loggerSinkConfiguration");

            if (bufferFileSizeLimitBytes.HasValue && bufferFileSizeLimitBytes < 0)
                throw new ArgumentException("Negative value provided; file size limit must be non-negative");

            if (string.IsNullOrEmpty(applicationName))
                throw new ArgumentException("Must supply an application name");

            var defaultedPeriod = period ?? NewRelicSink.DefaultPeriod;

            ILogEventSink sink;

            if (bufferBaseFilename == null)
                sink = new NewRelicSink(applicationName, batchPostingLimit, defaultedPeriod);
            else
            {
                //sink = new DurableNewRelicSink(bufferBaseFilename, applicationName, batchPostingLimit, defaultedPeriod,
                //    bufferFileSizeLimitBytes);

                throw new NotImplementedException("DurableNewRelicSink is not implemented yet.");
            }

            return loggerSinkConfiguration.Sink(sink, restrictedToMinimumLevel);
        }
Esempio n. 6
0
 /// <summary>
 ///     Creates a new <see cref="LogEvent" />
 /// </summary>
 public LogEvent(DateTimeOffset timestamp, LogEventLevel level, Exception exception, string message)
 {
     Timestamp = timestamp;
     Level = level;
     Exception = exception;
     Message = message;
 }
        public void Should_be_able_to_log_message(LogLevel logLevel, LogEventLevel logEventLevel)
        {
            _sut.Log(logLevel, () => "m");

            _logEvent.Level.Should().Be(logEventLevel);
            _logEvent.RenderMessage().Should().Be("m");
        }
        /// <summary>
        /// A sink that puts log events into a provided Azure Event Hub.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="eventHubClient">The Event Hub to use to insert the log entries to.</param>
        /// <param name="partitionKey">The partition key used to group log events in the Event Hub.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</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="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="writeInBatches">Use a periodic batching sink, as opposed to a synchronous one-at-a-time sink; this alters the partition
        /// key used for the events so is not enabled by default.</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>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration AzureEventHub(
            this LoggerSinkConfiguration loggerConfiguration,
            EventHubClient eventHubClient,
            string partitionKey = null,
            string outputTemplate = DefaultOutputTemplate,
            IFormatProvider formatProvider = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            bool writeInBatches = false,
            TimeSpan? period = null,
            int? batchPostingLimit = null
            )
        {
            if (loggerConfiguration == null)
                throw new ArgumentNullException("loggerConfiguration");
            if (eventHubClient == null)
                throw new ArgumentNullException("eventHubClient");
            if (outputTemplate == null)
                throw new ArgumentNullException("outputTemplate");

            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            var sink = writeInBatches ?
                (ILogEventSink) new AzureEventHubBatchingSink(
                    eventHubClient,
                    partitionKey ?? DefaultPartitionKey,
                    formatter,
                    batchPostingLimit ?? DefaultBatchPostingLimit,
                    period ?? DefaultPeriod) :
                new AzureEventHubSink(
                    eventHubClient,
                    partitionKey ?? DefaultPartitionKey,
                    formatter);

            return loggerConfiguration.Sink(sink, restrictedToMinimumLevel);
        }
        /// <summary>
        /// Adds a sink that sends log events via email.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="fromEmail">The email address emails will be sent from</param>
        /// <param name="toEmail">The email address emails will be sent to</param>
        /// <param name="mailServer">The SMTP email server to use</param>
        /// <param name="networkCredential">The network credentials to use to authenticate with mailServer</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        /// the default is "{Timestamp} [{Level}] {Message:l}{NewLine:l}{Exception:l}".</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</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="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration Email(
            this LoggerSinkConfiguration loggerConfiguration,
            string fromEmail, 
            string toEmail, 
            string mailServer,
            ICredentialsByHost networkCredential,
            string outputTemplate = DefaultOutputTemplate,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit = EmailSink.DefaultBatchPostingLimit,
            TimeSpan? period = null,
            IFormatProvider formatProvider = null)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
            if (fromEmail == null) throw new ArgumentNullException("fromEmail");
            if (toEmail == null) throw new ArgumentNullException("toEmail");
            if (mailServer == null) throw new ArgumentNullException("mailServer");

            var defaultedPeriod = period ?? EmailSink.DefaultPeriod;

            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return loggerConfiguration.Sink(
                new EmailSink(fromEmail, toEmail, mailServer, networkCredential, batchPostingLimit, defaultedPeriod, formatter),
                restrictedToMinimumLevel);
        }
        /// <summary>
        /// Adds a sink that writes log events as documents to Amazon Kinesis.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="kinesisClient"></param>
        /// <param name="streamName"></param>
        /// <param name="shardCount"></param>
        /// <param name="bufferBaseFilename"></param>
        /// <param name="bufferFileSizeLimitBytes"></param>
        /// <param name="batchPostingLimit"></param>
        /// <param name="period"></param>
        /// <param name="minimumLogEventLevel"></param>
        /// <param name="onLogSendError"></param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static LoggerConfiguration AmazonKinesis(
            this LoggerSinkConfiguration loggerConfiguration,
            IAmazonKinesis kinesisClient,
            string streamName,
            int? shardCount = null,
            string bufferBaseFilename = null,
            int? bufferFileSizeLimitBytes = null,
            int? batchPostingLimit = null,
            TimeSpan? period = null,
            LogEventLevel? minimumLogEventLevel = null,
            EventHandler<LogSendErrorEventArgs> onLogSendError = null)
        {
            if (streamName == null) throw new ArgumentNullException("streamName");

            var options = new KinesisStreamSinkOptions(streamName: streamName, shardCount: shardCount)
            {
                BufferFileSizeLimitBytes = bufferFileSizeLimitBytes,
                BufferBaseFilename = bufferBaseFilename,
                Period = period ?? KinesisStreamSinkOptions.DefaultPeriod,
                BatchPostingLimit = batchPostingLimit ?? KinesisStreamSinkOptions.DefaultBatchPostingLimit,
                MinimumLogEventLevel = minimumLogEventLevel ?? LevelAlias.Minimum,
                OnLogSendError = onLogSendError
            };

            return AmazonKinesis(loggerConfiguration, options, kinesisClient);
        }
        /// <summary>
        /// Adds a sink that writes log events (defaults to error and up) to the Raygun.io webservice. Properties are being send as data and the level is used as a tag.
        /// Your message is part of the custom data.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="raygunClient">An existing configured raygun client</param>
        /// <param name="tags">Specifies the tags to include with every log message. The log level will always be included as a tag.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink. By default set to Error as Raygun is mostly used for error reporting.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration Raygun(this LoggerSinkConfiguration loggerConfiguration, RaygunClient raygunClient, IEnumerable<string> tags, LogEventLevel restrictedToMinimumLevel = LogEventLevel.Error, IFormatProvider formatProvider = null)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));
            if (raygunClient == null) throw new ArgumentNullException(nameof(raygunClient));

            return loggerConfiguration.Sink(new RaygunSink(formatProvider, raygunClient, tags), restrictedToMinimumLevel);
        }
Esempio n. 12
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);
            }
        }
        /// <summary>
        /// Adds a sink that sends log events via email.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="fromEmail">The email address emails will be sent from</param>
        /// <param name="toEmail">The email address emails will be sent to</param>
        /// <param name="mailServer">The SMTP email server to use</param>
        /// <param name="networkCredential">The network credentials to use to authenticate with mailServer</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="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</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="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration Email(
            this LoggerSinkConfiguration loggerConfiguration,
            string fromEmail,
            string toEmail,
            string mailServer,
            ICredentialsByHost networkCredential,
            string outputTemplate = DefaultOutputTemplate,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit = EmailSink.DefaultBatchPostingLimit,
            TimeSpan? period = null,
            IFormatProvider formatProvider = null)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
            if (fromEmail == null) throw new ArgumentNullException("fromEmail");
            if (toEmail == null) throw new ArgumentNullException("toEmail");
            if (mailServer == null) throw new ArgumentNullException("mailServer");

            
            var connectionInfo = new EmailConnectionInfo
            {
                FromEmail = fromEmail,
                ToEmail = toEmail,
                MailServer = mailServer,
                NetworkCredentials = networkCredential
            };

            return Email(loggerConfiguration, connectionInfo, outputTemplate, restrictedToMinimumLevel, batchPostingLimit, period, formatProvider);
        }
        /// <summary>
        /// Adds a sink that writes log events as documents to a SignalR hub.
        /// 
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param><param name="context">The hub context.</param><param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</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="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <returns>
        /// Logger configuration, allowing configuration to continue.
        /// </returns>
        /// <exception cref="T:System.ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration SignalR(this LoggerSinkConfiguration loggerConfiguration, IHubContext context, LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose, int batchPostingLimit = 5, TimeSpan? period = null, IFormatProvider formatProvider = null)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));
            if (context == null) throw new ArgumentNullException(nameof(context));

            return loggerConfiguration.Sink(new SignalRLogSink(context, formatProvider), restrictedToMinimumLevel);
        }
		public AddSeqSinkCommand( LogEventLevel restrictedToMinimumLevel, int batchPostingLimit, TimeSpan? period, [Optional]string apiKey, [Optional]string bufferBaseFileName, long? bufferFileSizeLimitBytes ) : base( restrictedToMinimumLevel )
		{
			BatchPostingLimit = batchPostingLimit;
			Period = period;
			ApiKey = apiKey;
			BufferBaseFileName = bufferBaseFileName;
			BufferFileSizeLimitBytes = bufferFileSizeLimitBytes;
		}
 public static LoggerConfiguration DummyRollingFile(
     this LoggerSinkConfiguration loggerSinkConfiguration,
     ITextFormatter formatter,
     string pathFormat,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
 {
     return loggerSinkConfiguration.Sink(new DummyRollingFileSink(), restrictedToMinimumLevel);
 }
        /// <summary>
        /// Write log events to Glimpse
        /// </summary>
        /// <returns>Configuration object allowing method chaining.</returns>
        public static LoggerConfiguration Glimpse(this LoggerSinkConfiguration loggerConfiguration, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, IFormatProvider formatProvider = null)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
            
#pragma warning disable 618
            return loggerConfiguration.Sink(new GlimpseSink(GlimpseConfiguration.GetConfiguredMessageBroker, formatProvider), restrictedToMinimumLevel);
#pragma warning restore 618
        }
        public static LoggerConfiguration RollingFileAsJson(this LoggerSinkConfiguration sinkConfiguration, string pathFormat, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
        {
            if (sinkConfiguration == null)
                throw new ArgumentNullException("sinkConfiguration");

            var jsonSink = new RollingFileSink(pathFormat, new JsonFormatter(false, null, true), DefaultFileSizeLimitBytes, DefaultRetainedFileCountLimit);
            return sinkConfiguration.Sink(jsonSink, restrictedToMinimumLevel);
        }
        /// <summary>
        ///     Adds a sink that writes log events as documents using DocSet.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="connectionsStringName">The connectionsString name.</param>
        /// <param name="schemaName">The name of the database schema.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</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="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="propertiesAsTags">The properties as tags.</param>
        /// <param name="propertiesWhiteList">The properties filter.</param>
        /// <param name="options">The options.</param>
        /// <param name="indexMap">The index map.</param>
        /// <param name="enableDocSetLogging">if set to <c>true</c> [enable document set logging].</param>
        /// <returns>
        ///     Logger configuration, allowing configuration to continue.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// </exception>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration DocSet(
            this LoggerSinkConfiguration loggerConfiguration,
            string connectionsStringName,
            string schemaName = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit = 50,
            TimeSpan? period = null,
            IFormatProvider formatProvider = null,
            IEnumerable<string> propertiesAsTags = null,
            IEnumerable<string> propertiesWhiteList = null,
            IStorageOptions options = null,
            List<IIndexMap<LogEvent>> indexMap = null,
            bool enableDocSetLogging = false)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));
            if (connectionsStringName == null) throw new ArgumentNullException(nameof(connectionsStringName));

            if (options == null)
                options = new StorageOptions(
                    new ConnectionStrings().Get(connectionsStringName),
                    schemaName: schemaName);

            if (indexMap == null)
                indexMap = new List<IIndexMap<LogEvent>>
                {
                    new IndexMap<LogEvent>(nameof(LogEvent.Level), i => i.Level),
                    new IndexMap<LogEvent>(nameof(LogEvent.Timestamp), i => i.Timestamp.ToString("s"))
                };

            try
            {
                return loggerConfiguration.Sink(
                    new DocSetSink(
                        new DocStorage<LogEvent>(new SqlConnectionFactory(), options, new SqlBuilder(),
                            new JsonNetSerializer(), null /*new Md5Hasher()*/, indexMap),
                        batchPostingLimit,
                        period ?? DocSetSink.DefaultPeriod,
                        formatProvider,
                        propertiesAsTags ?? new[] {"CorrelationId", "App" /*, "SourceContext"*/},
                        propertiesWhiteList ??
                        new[] {/*"CorrelationId",*/ "App", "SourceContext" /*"Message", "DocSetKey"*/}),
                    restrictedToMinimumLevel);
            }
            catch (DbException)
            {
                // could not connect to the db, use a null docstorage instead
                return loggerConfiguration.Sink(
                    new DocSetSink(
                        null,
                        batchPostingLimit,
                        period ?? DocSetSink.DefaultPeriod,
                        formatProvider,
                        propertiesAsTags ?? new[] {"CorrelationId", "App" /*, "SourceContext"*/},
                        propertiesWhiteList ??
                        new[] {/*"CorrelationId",*/ "App", "SourceContext" /*"Message", "DocSetKey"*/}),
                    restrictedToMinimumLevel);
            }
        }
Esempio n. 20
0
 public static void Log(
     LogEventLevel level, 
     string area,
     object source,
     string messageTemplate, 
     params object[] propertyValues)
 {
     Sink?.Log(level, area, source, messageTemplate, propertyValues);
 }
        private const int DefaultRetainedFileCountLimit = 31; // A long month of logs

        /// <summary>
        ///     Writes log events to <see cref="IOutput" />.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="factory"></param>
        /// <param name="outputLogFilterProvider"></param>
        /// <param name="restrictedToMinimumLevel">
        ///     The minimum level for
        ///     events passed through the sink.
        /// </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 OutputModule(this LoggerSinkConfiguration sinkConfiguration,
            Func<IOutput> factory, Func<IOutputLogFilter> outputLogFilterProvider = null, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate = DefaultConsoleOutputTemplate, IFormatProvider formatProvider = null)
        {
            if (sinkConfiguration == null) throw new ArgumentNullException("sinkConfiguration");
            if (outputTemplate == null) throw new ArgumentNullException("outputTemplate");
            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
            return sinkConfiguration.Sink(new OutputSink(factory, formatter, outputLogFilterProvider), restrictedToMinimumLevel);
        }
 public static LoggerConfiguration DummyRollingFile(
     this LoggerAuditSinkConfiguration loggerSinkConfiguration,
     string pathFormat,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     string outputTemplate = null,
     IFormatProvider formatProvider = null)
 {
     return loggerSinkConfiguration.Sink(new DummyRollingFileAuditSink(), restrictedToMinimumLevel);
 }
 /// <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.</param>
 /// <param name="outputTemplate">A message template describing the format used to write to the sink.
 /// the default is "{Timestamp} [{Level}] {Message:l}{NewLine:l}{Exception:l}".</param>
 /// <returns>Configuration object allowing method chaining.</returns>
 public static LoggerConfiguration ColoredConsole(
     this LoggerSinkConfiguration sinkConfiguration,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     string outputTemplate = DefaultConsoleOutputTemplate)
 {
     if (sinkConfiguration == null) throw new ArgumentNullException("sinkConfiguration");
     if (outputTemplate == null) throw new ArgumentNullException("outputTemplate");
     return sinkConfiguration.Sink(new ColoredConsoleSink(outputTemplate), restrictedToMinimumLevel);
 }
        /// <summary>
        /// Adds a sink that writes log events (defaults to error and up) to the Raygun.io webservice. Properties are being send as data and the level is used as a tag.
        /// Your message is part of the custom data.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="applicationKey">The application key as found on the Raygun.io website.</param>
        /// <param name="wrapperExceptions">If you have common outer exceptions that wrap a valuable inner exception which you'd prefer to group by, you can specify these by providing a list.</param>
        /// <param name="userNameProperty">Specifies the property name to read the username from. By default it is UserName. Set to null if you do not want to use this feature.</param>
        /// <param name="applicationVersionProperty">Specifies the property to use to retrieve the application version from. You can use an enricher to add the application version to all the log events. When you specify null, Raygun will use the assembly version.</param> 
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink. By default set to Error as Raygun is mostly used for error reporting.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="tags">Specifies the tags to include with every log message. The log level will always be included as a tag.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration Raygun(this LoggerSinkConfiguration loggerConfiguration, string applicationKey, IEnumerable<Type> wrapperExceptions = null, string userNameProperty = "UserName", string applicationVersionProperty = "ApplicationVersion", LogEventLevel restrictedToMinimumLevel = LogEventLevel.Error, IFormatProvider formatProvider = null, IEnumerable<string> tags = null)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));

            if (string.IsNullOrWhiteSpace(applicationKey))
                throw new ArgumentNullException(nameof(applicationKey));

            return loggerConfiguration.Sink(new RaygunSink(formatProvider, applicationKey, wrapperExceptions, userNameProperty, applicationVersionProperty, tags), restrictedToMinimumLevel);
        }
        /// <summary>
        /// Adds a sink that writes log events as documents to a MongoDb database.
        /// </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>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration Log4Net(
            this LoggerSinkConfiguration loggerConfiguration,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            IFormatProvider formatProvider = null)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");

            return loggerConfiguration.Sink(new Log4NetSink(formatProvider), restrictedToMinimumLevel);
        }
        public static LoggerConfiguration RollingFileAsText(this LoggerSinkConfiguration sinkConfiguration, string pathFormat, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
        {
            if (sinkConfiguration == null)
                throw new ArgumentNullException("sinkConfiguration");

            var formatter = new MessageTemplateTextFormatter(DefaultOutputTemplate, null);
            var sink = new RollingFileSink(pathFormat, formatter, DefaultFileSizeLimitBytes, DefaultRetainedFileCountLimit);
            return sinkConfiguration.Sink(sink, restrictedToMinimumLevel);
        }
 /// <summary>
 /// Adds a sink that writes log events against Microsoft Application Insights for the provided <paramref name="instrumentationKey"/>.
 /// </summary>
 /// <param name="loggerConfiguration">The logger configuration.</param>
 /// <param name="instrumentationKey">Required Application Insights instrumentation key.</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>
 /// <returns>
 /// Logger configuration, allowing configuration to continue.
 /// </returns>
 /// <exception cref="System.ArgumentNullException">loggerConfiguration</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">instrumentationKey;Cannot be empty or null.</exception>
 public static LoggerConfiguration ApplicationInsights(
     this LoggerSinkConfiguration loggerConfiguration,
     string instrumentationKey,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     IFormatProvider formatProvider = null)
 {
     if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
     return loggerConfiguration.Sink(new ApplicationInsightsSink(CreateTelemetryClientFromInstrumentationkey(instrumentationKey), formatProvider), restrictedToMinimumLevel);
 }
        public void Should_be_able_to_log_message_and_exception(LogLevel logLevel, LogEventLevel logEventLevel)
        {
            var exception = new Exception("e");
            _sut.Log(logLevel, () => "m", exception);

            _logEvent.Level.Should().Be(logEventLevel);
            _logEvent.RenderMessage().Should().Be("m");
            _logEvent.Exception.Should().Be(exception);
        }
 /// <summary>
 /// Writes log events to <see cref="System.Console"/>, using pretty printing to display inline event data.
 /// </summary>
 /// <param name="sinkConfiguration">Logger sink configuration.</param>
 /// <param name="restrictedToMinimumLevel">The minimum level for
 /// events passed through the sink.</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 LiterateConsole(
     this LoggerSinkConfiguration sinkConfiguration,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     string outputTemplate = DefaultOutputTemplate,
     IFormatProvider formatProvider = null)
 {
     if (sinkConfiguration == null) throw new ArgumentNullException("sinkConfiguration");
     if (outputTemplate == null) throw new ArgumentNullException("outputTemplate");
     return sinkConfiguration.Sink(new LiterateConsoleSink(outputTemplate, formatProvider), restrictedToMinimumLevel);
 }
        /// <summary>
        /// Write log events to a series of files. Each file will be named according to
        /// the date of the first log entry written to it. Only simple date-based rolling is
        /// currently supported.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="pathFormat">String describing the location of the log files,
        /// with {Date} in the place of the file date. E.g. "Logs\myapp-{Date}.log" will result in log
        /// files such as "Logs\myapp-2013-10-20.log", "Logs\myapp-2013-10-21.log" and so on.</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="fileSizeLimitBytes">The maximum size, in bytes, to which any single log file will be allowed to grow.
        /// For unrestricted growth, pass null. The default is 1 GB.</param>
        /// <param name="retainedFileDurationLimit">The maximum timespan of log files that will be retained,
        /// including the current log file. The value should folowing TimeSpan format (d.hh.mm.ss).The default is 7 days</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        /// <remarks>The file will be written using the UTF-8 character set.</remarks>
        public static LoggerConfiguration SizeRollingFile(this LoggerSinkConfiguration sinkConfiguration, string pathFormat, TimeSpan? retainedFileDurationLimit = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, string outputTemplate = DefaultOutputTemplate,
            IFormatProvider formatProvider = null, long? fileSizeLimitBytes = null, bool supportAsync = false, int? bufferSize = null, int? maxRetries = null)
        {

            var templateFormatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return SizeRollingFile(sinkConfiguration, templateFormatter, pathFormat, retainedFileDurationLimit,
                restrictedToMinimumLevel, outputTemplate, formatProvider, fileSizeLimitBytes, supportAsync, bufferSize, maxRetries);
        }
 public static IActionResult LogAndReturnBadRequest(this ControllerBase controller, ILogger logger, string message, LogEventLevel logLevel = LogEventLevel.Error)
 {
     logger.LogByLevel(message, logLevel);
     return(controller.BadRequest(message));
 }
 internal static void SetLogLevel(LogEventLevel logLevel)
 {
     LoggingLevelSwitch.MinimumLevel = logLevel;
 }
Esempio n. 33
0
 public NancyLogger(Type sourceType, LogEventLevel minimumLevel, string loggerStateNamespace, Func <string, LogEventLevel, bool> filter,
                    LogEventSendMode sendMode, RendingConfiguration renderingOptions, ILogPayloadSender logPayloadSender)
     : base(sourceType, minimumLevel, loggerStateNamespace, filter, sendMode, renderingOptions, logPayloadSender)
 {
 }
Esempio n. 34
0
 public NLogSinkOptions UseMinimumLevelForType <T>(LogEventLevel level) => UseMinimumLevelForType(typeof(T), level);
Esempio n. 35
0
 public bool IsEnabled(LogEventLevel level)
 {
     return(_output.IsEnabled((SerilogLogEventLevel)level));
 }
Esempio n. 36
0
 public void SetMinimumLevel(LogEventLevel level)
 {
     LevelSwitch.MinimumLevel = level;
 }
Esempio n. 37
0
 public DynamicLogSink(ILogEventSink innerSink, LogEventLevel filteredLevel = LogEventLevel.Information)
 {
     this.innerSink     = innerSink;
     this.filteredLevel = filteredLevel;
 }
Esempio n. 38
0
 /// <summary>
 /// 获取输出配置
 /// </summary>
 /// <param name="configuration">日志配置</param>
 /// <param name="level">日志级别</param>
 /// <param name="path">路径</param>
 /// <param name="name">名称</param>
 private static LoggerConfiguration GetOutputConfiguration(LoggerConfiguration configuration, LogEventLevel level, string path, string name) =>
 configuration.Filter.ByIncludingOnly(p => p.Level.Equals(level)).WriteTo.RollingFile(
     Path.Combine($"{path}\\{name}\\{DateTime.Now:yyyy-MM-dd}", name + "-{Hour}.log"), level);
Esempio n. 39
0
 public void Write(LogEventLevel level, string messageTemplate, params object[] propertyValues)
 {
     Write(level, null, messageTemplate, propertyValues);
 }
        public int CalculatePriority(LogEventLevel level)
        {
            var severity = MapLogLevelToSeverity(level);

            return(((int)this.facility * 8) + (int)severity);
        }
Esempio n. 41
0
        static LoggerConfiguration ConfigureFile(
            this Func <ILogEventSink, LogEventLevel, LoggingLevelSwitch, LoggerConfiguration> addSink,
            ITextFormatter formatter,
            string path,
            LogEventLevel restrictedToMinimumLevel,
            long?fileSizeLimitBytes,
            LoggingLevelSwitch levelSwitch,
            bool buffered,
            bool propagateExceptions,
            bool shared,
            TimeSpan?flushToDiskInterval,
            Encoding encoding,
            RollingInterval rollingInterval,
            bool rollOnFileSizeLimit,
            int?retainedFileCountLimit)
        {
            if (addSink == null)
            {
                throw new ArgumentNullException(nameof(addSink));
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0)
            {
                throw new ArgumentException("Negative value provided; file size limit must be non-negative.", nameof(fileSizeLimitBytes));
            }
            if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1)
            {
                throw new ArgumentException("At least one file must be retained.", nameof(retainedFileCountLimit));
            }
            if (shared && buffered)
            {
                throw new ArgumentException("Buffered writes are not available when file sharing is enabled.", nameof(buffered));
            }

            ILogEventSink sink;

            if (rollOnFileSizeLimit || rollingInterval != RollingInterval.Infinite)
            {
                sink = new RollingFileSink(path, formatter, fileSizeLimitBytes, retainedFileCountLimit, encoding, buffered, shared, rollingInterval, rollOnFileSizeLimit);
            }
            else
            {
                try
                {
#pragma warning disable 618
                    if (shared)
                    {
                        sink = new SharedFileSink(path, formatter, fileSizeLimitBytes);
                    }
                    else
                    {
                        sink = new FileSink(path, formatter, fileSizeLimitBytes, buffered: buffered);
                    }
#pragma warning restore 618
                }
                catch (Exception ex)
                {
                    SelfLog.WriteLine("Unable to open file sink for {0}: {1}", path, ex);

                    if (propagateExceptions)
                    {
                        throw;
                    }

                    return(addSink(new NullSink(), LevelAlias.Maximum, null));
                }
            }

            if (flushToDiskInterval.HasValue)
            {
                sink = new PeriodicFlushToDiskSink(sink, flushToDiskInterval.Value);
            }

            return(addSink(sink, restrictedToMinimumLevel, levelSwitch));
        }
 protected SinkWrapper(LogEventLevel logEventLevel)
 {
     LogEventLevel = logEventLevel;
 }
Esempio n. 43
0
 public void Write(LogEventLevel level, string messageTemplate, params object[] propertyValues)
 {
     throw new NotImplementedException();
 }
Esempio n. 44
0
 private static LoggerConfiguration LoggerConfigure(this LoggerConfiguration logger, LogEventLevel level) => logger.WriteTo.Logger(LoggerDelegate(level));
Esempio n. 45
0
 private static Action <LoggerSinkConfiguration> ConfigureDelegate(LogEventLevel level) => a => a.RollingFile($"File/logs/log-{{Date}}-{level.ToString()}.txt");
        /// <summary>
        /// Adds a sink that writes log events to a http://getseq.net Seq event server.
        /// </summary>
        /// <param name="loggerSinkConfiguration">The logger configuration.</param>
        /// <param name="serverUrl">The base URL of the Seq server that log events will be written to.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required
        /// in order to write an event to the sink.</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="apiKey">A Seq <i>API key</i> that authenticates the client to the Seq server.</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 Seq server. Specify null for no limit.
        /// The default is 265 KB.</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="messageHandler">Used to construct the HttpClient that will be used to send the log meesages to Seq.</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>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration Seq(
            this LoggerSinkConfiguration loggerSinkConfiguration,
            string serverUrl,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit                  = SeqSink.DefaultBatchPostingLimit,
            TimeSpan?period                        = null,
            string apiKey                          = null,
            string bufferBaseFilename              = null,
            long?bufferFileSizeLimitBytes          = null,
            long?eventBodyLimitBytes               = 256 * 1024,
            LoggingLevelSwitch controlLevelSwitch  = null,
            HttpMessageHandler messageHandler      = null,
            long?retainedInvalidPayloadsLimitBytes = null)
        {
            if (loggerSinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerSinkConfiguration));
            }
            if (serverUrl == null)
            {
                throw new ArgumentNullException(nameof(serverUrl));
            }
            if (bufferFileSizeLimitBytes.HasValue && bufferFileSizeLimitBytes < 0)
            {
                throw new ArgumentException("Negative value provided; file size limit must be non-negative");
            }

            var defaultedPeriod = period ?? SeqSink.DefaultPeriod;

            ILogEventSink sink;

            if (bufferBaseFilename == null)
            {
                sink = new SeqSink(
                    serverUrl,
                    apiKey,
                    batchPostingLimit,
                    defaultedPeriod,
                    eventBodyLimitBytes,
                    controlLevelSwitch,
                    messageHandler);
            }
            else
            {
#if DURABLE
                sink = new DurableSeqSink(
                    serverUrl,
                    bufferBaseFilename,
                    apiKey,
                    batchPostingLimit,
                    defaultedPeriod,
                    bufferFileSizeLimitBytes,
                    eventBodyLimitBytes,
                    controlLevelSwitch,
                    messageHandler,
                    retainedInvalidPayloadsLimitBytes);
#else
                // We keep the API consistent for easier packaging and to support bait-and-switch.
                throw new NotSupportedException("Durable log shipping is not supported on this platform.");
#endif
            }

            return(loggerSinkConfiguration.Sink(sink, restrictedToMinimumLevel));
        }
Esempio n. 47
0
 public NLogSinkOptions UseMinimumLevelForCategoryName <T>(LogEventLevel level) => UseMinimumLevelForCategoryName(typeof(T), level);
Esempio n. 48
0
 private static Action <LoggerConfiguration> LoggerDelegate(LogEventLevel level) => lg => lg.Filter.ByIncludingOnly(p => p.Level == level).WriteTo.Async(a => ConfigureDelegate(level));
Esempio n. 49
0
        public static void UseSerilog <TContext>(this IPipeConfigurator <TContext> configurator, LogEventLevel logAsLevel = LogEventLevel.Information, ILogger logger = null, Func <bool> shouldExecute = null)
            where TContext : IContext <IMessage>
        {
            if (logger == null && configurator.DependencyScope == null)
            {
                throw new DependencyScopeNotConfiguredException($"{nameof(ILogger)} is not provided and IDependencyScope is not configured, Please ensure {nameof(ILogger)} is registered properly if you are using IoC container, otherwise please pass {nameof(ILogger)} as parameter");
            }
            logger = logger ?? configurator.DependencyScope.Resolve <ILogger>();

            configurator.AddPipeSpecification(new SerilogMiddlewareSpecification <TContext>(logger, logAsLevel, shouldExecute));
        }
        /// <summary>
        /// Adds a durable sink that sends log events using HTTP POST over the network. A durable
        /// sink will persist log events on disk in buffer files before sending them over the
        /// network, thus protecting against data loss after a system or process restart. The
        /// buffer files will use a rolling behavior defined by the file size specified in
        /// <paramref name="bufferFileSizeLimitBytes"/>, i.e. a new buffer file is created when
        /// current has passed its limit. The maximum number of retained files is defined by
        /// <paramref name="retainedBufferFileCountLimit"/>, and when that limit is reached the
        /// oldest file is dropped to make room for a new.
        /// </summary>
        /// <param name="sinkConfiguration">The logger configuration.</param>
        /// <param name="requestUri">The URI the request is sent to.</param>
        /// <param name="bufferBaseFileName">
        /// The relative or absolute 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"/>*.json", which should
        /// not clash with any other file names in the same directory. Default value is "Buffer".
        /// </param>
        /// <param name="bufferFileSizeLimitBytes">
        /// The approximate maximum size, in bytes, to which a buffer file will be allowed to grow.
        /// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial
        /// events, the last event within the limit will be written in full even if it exceeds the
        /// limit.
        /// </param>
        /// <param name="bufferFileShared">
        /// Allow the buffer file to be shared by multiple processes. Default value is false.
        /// </param>
        /// <param name="retainedBufferFileCountLimit">
        /// The maximum number of buffer files that will be retained, including the current buffer
        /// file. Under normal operation only 2 files will be kept, however if the log server is
        /// unreachable, the number of files specified by <paramref name="retainedBufferFileCountLimit"/>
        /// will be kept on the file system. For unlimited retention, pass null. Default value is 31.
        /// </param>
        /// <param name="batchPostingLimit">
        /// The maximum number of events to post in a single batch. Default value is 1000.
        /// </param>
        /// <param name="period">
        /// The time to wait between checking for event batches. Default value is 2 seconds.
        /// </param>
        /// <param name="textFormatter">
        /// The formatter rendering individual log events into text, for example JSON. Default
        /// value is <see cref="NormalRenderedTextFormatter"/>.
        /// </param>
        /// <param name="batchFormatter">
        /// The formatter batching multiple log events into a payload that can be sent over the
        /// network. Default value is <see cref="DefaultBatchFormatter"/>.
        /// </param>
        /// <param name="restrictedToMinimumLevel">
        /// The minimum level for events passed through the sink. Default value is
        /// <see cref="LevelAlias.Minimum"/>.
        /// </param>
        /// <param name="httpClient">
        /// A custom <see cref="IHttpClient"/> implementation. Default value is
        /// <see cref="HttpClient"/>.
        /// </param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        public static LoggerConfiguration Site24x7UsingFileSizeRolledBuffers(
            this LoggerSinkConfiguration sinkConfiguration,
            string requestUri,
            string minimumLogLevel           = null,
            string bufferBaseFileName        = "Buffer",
            long?bufferFileSizeLimitBytes    = 1024 * 1024 * 1024,
            bool bufferFileShared            = false,
            int?retainedBufferFileCountLimit = 31,
            int batchPostingLimit            = 1000,
            TimeSpan?period = null,
            ITextFormatter textFormatter   = null,
            IBatchFormatter batchFormatter = null,

            IHttpClient httpClient = null)
        {
            LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose;

            if (minimumLogLevel == null)
            {
                restrictedToMinimumLevel = LogEventLevel.Verbose;
            }
            else if (minimumLogLevel == "Debug")
            {
                restrictedToMinimumLevel = LogEventLevel.Debug;
            }
            else if (minimumLogLevel == "Information")
            {
                restrictedToMinimumLevel = LogEventLevel.Information;
            }
            else if (minimumLogLevel == "Warning")
            {
                restrictedToMinimumLevel = LogEventLevel.Warning;
            }
            else if (minimumLogLevel == "Error")
            {
                restrictedToMinimumLevel = LogEventLevel.Error;
            }
            else if (minimumLogLevel == "Fatal")
            {
                restrictedToMinimumLevel = LogEventLevel.Fatal;
            }
            else
            {
                restrictedToMinimumLevel = LogEventLevel.Verbose;
            }

            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }

            // Default values
            period         = period ?? TimeSpan.FromMilliseconds(1);
            textFormatter  = textFormatter ?? new NormalRenderedTextFormatter();
            batchFormatter = batchFormatter ?? new DefaultBatchFormatter();
            httpClient     = httpClient ?? new DefaultHttpClient();

            var sink = new FileSizeRolledDurableHttpSink(
                requestUri: requestUri,
                bufferBaseFileName: bufferBaseFileName,
                bufferFileSizeLimitBytes: bufferFileSizeLimitBytes,
                bufferFileShared: bufferFileShared,
                retainedBufferFileCountLimit: retainedBufferFileCountLimit,
                batchPostingLimit: batchPostingLimit,
                period: period.Value,
                textFormatter: textFormatter,
                batchFormatter: batchFormatter,
                httpClient: httpClient);

            return(sinkConfiguration.Sink(sink, restrictedToMinimumLevel));
        }
Esempio n. 51
0
 public AutoTestNodeConfiguration(LogEventLevel verbosity = LogEventLevel.Verbose)
     : base("AutoTest", new AutoTestNodeNetworkAddress(), verbosity)
 {
 }
Esempio n. 52
0
        private static LoggerConfiguration ConfigureMinimumLevel(this LoggerConfiguration loggerConfiguration, LogEventLevel minimumLevel)
        {
            loggerConfiguration = minimumLevel switch
            {
                LogEventLevel.Verbose => loggerConfiguration.MinimumLevel.Verbose(),
                LogEventLevel.Debug => loggerConfiguration.MinimumLevel.Debug(),
                LogEventLevel.Information => loggerConfiguration.MinimumLevel.Information(),
                LogEventLevel.Warning => loggerConfiguration.MinimumLevel.Warning(),
                LogEventLevel.Error => loggerConfiguration.MinimumLevel.Error(),
                LogEventLevel.Fatal => loggerConfiguration.MinimumLevel.Fatal(),
                _ => throw new NotImplementedException()
            };

            return(loggerConfiguration.MinimumLevel.Override("Microsoft.AspNetCore", minimumLevel)
                   .MinimumLevel.Override("System", minimumLevel)
                   .MinimumLevel.Override("Microsoft", minimumLevel)
                   .MinimumLevel.Override("Microsoft.Hosting.Lifetime", minimumLevel));
        }
Esempio n. 53
0
 /// <summary>
 /// Checks if given log level is enabled.
 /// </summary>
 /// <param name="level">The log event level.</param>
 /// <param name="area">The log area.</param>
 /// <returns><see langword="true"/> if given log level is enabled.</returns>
 public static bool IsEnabled(LogEventLevel level, string area)
 {
     return(Sink?.IsEnabled(level, area) == true);
 }
 public static IActionResult LogAndReturnServiceUnavailable(this ControllerBase controller, ILogger logger, string message, LogEventLevel logLevel = LogEventLevel.Error)
 {
     logger.LogByLevel(message, logLevel);
     return(new ServiceUnavailableResult(message));
 }
Esempio n. 55
0
 public LogEventArgs(LogEventLevel logLevel, string contents) : base(contents)
 {
     Level    = logLevel;
     Contents = contents;
 }
Esempio n. 56
0
 public bool IsEnabled(LogEventLevel level)
 {
     throw new NotImplementedException();
 }
Esempio n. 57
0
        public static LoggerConfiguration SetDefaultLevel(this LoggerConfiguration loggerConfig, LogEventLevel defaultLevel = LogEventLevel.Information)
        {
#if DEBUG
            return(loggerConfig.MinimumLevel.Debug());
#else
            var           logLevel = Environment.GetEnvironmentVariable("CHOCOLATEYGUI__LOGLEVEL");
            LogEventLevel logEventLevel;
            if (string.IsNullOrWhiteSpace(logLevel) || !Enum.TryParse(logLevel, true, out logEventLevel))
            {
                loggerConfig.MinimumLevel.Is(defaultLevel);
            }
            else
            {
                loggerConfig.MinimumLevel.Is(logEventLevel);
            }

            return(loggerConfig);
#endif
        }