/// <summary>
        /// Adds a sink that writes log events as documents to a CouchDB database.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="databaseUrl">The URL of a created CouchDB database 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="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="databaseUsername">The username to authenticate with the database (if needed).</param>
        /// <param name="databasePassword">The password to use to authenticate (if needed)</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration CouchDB(
            this LoggerSinkConfiguration loggerConfiguration,
            string databaseUrl,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit          = CouchDBSink.DefaultBatchPostingLimit,
            TimeSpan?period                = null,
            IFormatProvider formatProvider = null,
            string databaseUsername        = null,
            string databasePassword        = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException("loggerConfiguration");
            }
            if (databaseUrl == null)
            {
                throw new ArgumentNullException("databaseUrl");
            }
            if (databaseUsername != null && databasePassword == null)
            {
                throw new ArgumentNullException("databasePassword");
            }
            if (databaseUsername == null && databasePassword != null)
            {
                throw new ArgumentNullException("databaseUsername");
            }

            var defaultedPeriod = period ?? CouchDBSink.DefaultPeriod;

            return(loggerConfiguration.Sink(
                       new CouchDBSink(
                           databaseUrl,
                           batchPostingLimit,
                           defaultedPeriod,
                           formatProvider,
                           databaseUsername,
                           databasePassword),
                       restrictedToMinimumLevel));
        }
 /// <summary>
 /// Adds Grafana Loki gRPC sink.
 /// </summary>
 /// <param name="sinkLoggerConfiguration"></param>
 /// <param name="grpcEndpoint">host:port for gRPC</param>
 /// <param name="labelProvider">Custom ILogLabelProvider implementation</param>
 /// <param name="period">The time to wait between checking for event batches. Default value is 2 seconds.</param>
 /// <param name="queueLimit">The maximum number of events stored in the queue in memory, waiting to be posted over the network. Default value is infinitely.</param>
 /// <param name="batchSizeLimit">The maximum number of events to post in a single batch. Default value is 1000.</param>
 /// <param name="restrictedToMinimumLevel">Minimum level for events passing through the sink</param>
 /// <param name="stackTraceAsLabel">Indicates if exception stacktrace should be sent as a label</param>
 /// <returns></returns>
 public static LoggerConfiguration LokigRPC(
     this LoggerSinkConfiguration sinkLoggerConfiguration,
     string grpcEndpoint,
     ILogLabelProvider labelProvider,
     TimeSpan period,
     int queueLimit,
     int batchSizeLimit,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     bool stackTraceAsLabel = false
     )
 {
     return(sinkLoggerConfiguration.Sink(
                new LokigRpcClient(
                    grpcEndpoint,
                    labelProvider,
                    queueLimit,
                    batchSizeLimit,
                    period,
                    stackTraceAsLabel
                    ), restrictedToMinimumLevel
                ));
 }
Beispiel #3
0
        /// <summary>
        /// Adds a sink that sends log events to Datadog.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="apiKey">Your Datadog API key.</param>
        /// <param name="source">The integration name.</param>
        /// <param name="service">The service name.</param>
        /// <param name="host">The host name.</param>
        /// <param name="tags">Custom tags.</param>
        /// <param name="configuration">The Datadog logs client configuration.</param>
        /// <returns>Logger configuration</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration DatadogLogs(
            this LoggerSinkConfiguration loggerConfiguration,
            string apiKey,
            string source  = null,
            string service = null,
            string host    = null,
            string[] tags  = null,
            DatadogConfiguration configuration = null,
            LogEventLevel logLevel             = LevelAlias.Minimum)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                throw new ArgumentNullException(nameof(apiKey));
            }

            configuration = (configuration != null) ? configuration : new DatadogConfiguration();
            return(loggerConfiguration.Sink(new DatadogSink(apiKey, source, service, host, tags, configuration), logLevel));
        }
Beispiel #4
0
        /// <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="toEmails">The email addresses 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,
            IEnumerable <string> toEmails,
            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 (toEmails == null)
            {
                throw new ArgumentNullException("toEmails");
            }
            if (mailServer == null)
            {
                throw new ArgumentNullException("mailServer");
            }

            var connectionInfo = new EmailConnectionInfo
            {
                FromEmail          = fromEmail,
                ToEmail            = string.Join(";", toEmails),
                MailServer         = mailServer,
                NetworkCredentials = networkCredential
            };

            return(Email(loggerConfiguration, connectionInfo, outputTemplate, restrictedToMinimumLevel, batchPostingLimit, period, formatProvider));
        }
Beispiel #5
0
        public static LoggerConfiguration Http(this LoggerSinkConfiguration loggerConfiguration,
                                               string api,
                                               string token,
                                               LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
                                               int batchPostingLimit = SerilogHttpSink.DefaultBatchPostingLimit,
                                               TimeSpan?period       = null)
        {
            if (loggerConfiguration == null)
            {
                throw new SpiderException($"{nameof(loggerConfiguration)} should not be null.");
            }

            var defaultedPeriod = period ?? SerilogHttpSink.DefaultPeriod;

            return(loggerConfiguration.Sink(
                       new SerilogHttpSink(
                           api,
                           token,
                           batchPostingLimit,
                           defaultedPeriod),
                       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.</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="retainedFileCountLimit">The maximum number of log files that will be retained,
        /// including the current log file. For unlimited retention, pass null. The default is 31.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        /// <remarks>The file will be written using the UTF-8 character set.</remarks>
        public static LoggerConfiguration RollingFile(
            this LoggerSinkConfiguration sinkConfiguration,
            string pathFormat,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate          = DefaultOutputTemplate,
            IFormatProvider formatProvider = null,
            long?fileSizeLimitBytes        = DefaultFileSizeLimitBytes,
            int?retainedFileCountLimit     = DefaultRetainedFileCountLimit)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException("sinkConfiguration");
            }
            if (outputTemplate == null)
            {
                throw new ArgumentNullException("outputTemplate");
            }
            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
            var sink      = new RollingFileSink(pathFormat, formatter, fileSizeLimitBytes, retainedFileCountLimit);

            return(sinkConfiguration.Sink(sink, restrictedToMinimumLevel));
        }
        /// <summary>
        /// Adds a sink that writes log events to a table in a PostgreSQL database.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="connectionString">The connection string to the database where to store the events.</param>
        /// <param name="tableName">Name of the table to store the events in.</param>
        /// <param name="schemaName">Name of the schema for the table to store the data in. The default is 'dbo'.</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>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration PostgreSqlServer(
            this LoggerSinkConfiguration loggerConfiguration,
            string connectionString,
            string tableName,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit = PostgreSqlSink.DefaultBatchPostingLimit,
            TimeSpan?period       = null,
            string schemaName     = "public"
            )
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }

            var defaultedPeriod = period ?? PostgreSqlSink.DefaultPeriod;

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException(nameof(connectionString));
            }
            try
            {
                return(loggerConfiguration.Sink(
                           new PostgreSqlSink(
                               connectionString,
                               tableName,
                               batchPostingLimit,
                               defaultedPeriod,
                               schemaName
                               ),
                           restrictedToMinimumLevel));
            }
            catch (Exception ex)
            {
                SelfLog.WriteLine(ex.Message);
                throw;
            }
        }
        /// <summary>
        ///     Adds a sink that writes log events to a SQLite database.
        /// </summary>
        /// <param name="loggerConfiguration"> The logger configuration. </param>
        /// <param name="app">                </param>
        /// <exception cref="ArgumentNullException"> A required parameter is null. </exception>
        public static LoggerConfiguration SQLite(this LoggerSinkConfiguration loggerConfiguration)
        {
            if (string.IsNullOrWhiteSpace(LoggerConfig.SQLiteFilePath))
            {
                SelfLog.WriteLine($"Invalid {LoggerConfig.SQLiteFilePath}");
                throw new ArgumentNullException(nameof(LoggerConfig.SQLiteFilePath));
            }

            try
            {
                // Make sure folder is created
                var sqliteDbFile = new FileInfo(LoggerConfig.SQLiteFilePath.GetFullPath());
                sqliteDbFile.Directory?.Create();

                return(loggerConfiguration.Sink(new SQLiteSink(), LoggerConfig.SQLiteLogMinimumLevelEnum));
            }
            catch (Exception ex)
            {
                SelfLog.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #9
0
 /// <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>
 /// <param name="standardErrorFromLevel">Specifies the level at which events will be written to standard error.</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,
     LogEventLevel?standardErrorFromLevel = null)
 {
     if (sinkConfiguration == null)
     {
         throw new ArgumentNullException(nameof(sinkConfiguration));
     }
     if (outputTemplate == null)
     {
         throw new ArgumentNullException(nameof(outputTemplate));
     }
     return(sinkConfiguration.Console(
                outputTemplate: outputTemplate,
                formatProvider: formatProvider,
                standardErrorFromLevel: standardErrorFromLevel,
                theme: SystemConsoleTheme.Literate,
                restrictedToMinimumLevel: restrictedToMinimumLevel));
 }
        /// <summary>
        /// Adds a sink that writes log events to a TCP syslog server, optionally over a TLS-secured
        /// </summary>
        /// <param name="loggerSinkConfig">The logger configuration</param>
        /// <param name="host">Hostname of the syslog server</param>
        /// <param name="port">Port the syslog server is listening on</param>
        /// <param name="appName">The name of the application. Defaults to the current process name</param>
        /// <param name="framingType">How to frame/delimit syslog messages for the wire</param>
        /// <param name="format">The syslog message format to be used</param>
        /// <param name="facility">The category of the application</param>
        /// <param name="secureProtocols">
        /// SSL/TLS protocols to be used for a secure channel. Set to None for an unsecured connection
        /// </param>
        /// <param name="certProvider">Optionally used to present the syslog server with a client certificate</param>
        /// <param name="certValidationCallback">
        /// Optional callback used to validate the syslog server's certificate. If null, the system default
        /// will be used
        /// </param>
        /// <param name="outputTemplate">A message template describing the output messages
        /// <seealso cref="https://github.com/serilog/serilog/wiki/Formatting-Output"/>
        /// </param>
        public static LoggerConfiguration TcpSyslog(this LoggerSinkConfiguration loggerSinkConfig,
                                                    string host, int port        = 1468, string appName = null, FramingType framingType = FramingType.OCTET_COUNTING,
                                                    SyslogFormat format          = SyslogFormat.RFC5424, Facility facility = Facility.Local0,
                                                    SslProtocols secureProtocols = SslProtocols.Tls12, ICertificateProvider certProvider = null,
                                                    RemoteCertificateValidationCallback certValidationCallback = null,
                                                    string outputTemplate = null)
        {
            var formatter = GetFormatter(format, appName, facility, outputTemplate);

            var config = new SyslogTcpConfig
            {
                Host                   = host,
                Port                   = port,
                Formatter              = formatter,
                Framer                 = new MessageFramer(framingType),
                SecureProtocols        = secureProtocols,
                CertProvider           = certProvider,
                CertValidationCallback = certValidationCallback
            };

            return(TcpSyslog(loggerSinkConfig, config));
        }
        /// <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("loggerConfiguration");
            }

            if (string.IsNullOrWhiteSpace(applicationKey))
            {
                throw new ArgumentNullException("applicationKey");
            }

            return(loggerConfiguration.Sink(
                       new RaygunSink(formatProvider, applicationKey, wrapperExceptions, userNameProperty, applicationVersionProperty, tags),
                       restrictedToMinimumLevel));
        }
Beispiel #12
0
        /// <summary>
        ///     Adds a sink that writes log events to a Azure Log Analytics.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="workspaceId">Workspace Id from Azure OMS Portal connected sources.</param>
        /// <param name="authenticationId">
        ///     Primary or Secondary key from Azure OMS Portal connected sources.
        /// </param>
        /// <param name="loggerSettings">Optional configuration settings for logger</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="levelSwitch">
        /// A switch allowing the pass-through minimum level to be changed at runtime.
        /// </param>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration AzureAnalytics(
            this LoggerSinkConfiguration loggerConfiguration,
            string workspaceId,
            string authenticationId,
            ConfigurationSettings loggerSettings,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            LoggingLevelSwitch levelSwitch         = null)
        {
            if (string.IsNullOrEmpty(workspaceId))
            {
                throw new ArgumentNullException(nameof(workspaceId));
            }
            if (string.IsNullOrEmpty(authenticationId))
            {
                throw new ArgumentNullException(nameof(authenticationId));
            }

            return(loggerConfiguration.Sink(
                       new AzureLogAnalyticsSink(workspaceId, authenticationId, loggerSettings),
                       restrictedToMinimumLevel,
                       levelSwitch));
        }
        /// <summary>
        /// Adds a durable sink that will send log events to Grafana Loki. 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="uri">
        /// The root URI of Loki.
        /// </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 for a specific time interval will be
        /// allowed to grow. By default no limit will be applied.
        /// </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="labels">
        /// The globals log event labels, which will be user for enriching all requests.
        /// </param>
        /// <param name="excludedLabels">
        /// Keys, which would be excluded from a the label list in a payload.
        /// </param>
        /// <param name="credentials">
        /// Auth <see cref="LokiCredentials"/>.
        /// </param>
        /// <param name="outputTemplate">
        /// A message template describing the format used to write to the sink.
        /// Default value is <code>"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"</code>.
        /// </param>
        /// <param name="restrictedToMinimumLevel">
        /// The minimum level for events passed through the sink.
        /// Default value is <see cref="LevelAlias.Minimum"/>.
        /// </param>
        /// <param name="batchPostingLimit">
        /// The maximum number of events to post in a single batch. Default value is 1000.
        /// </param>
        /// <param name="queueLimit">
        /// The maximum number of events stored in the queue in memory, waiting to be posted over
        /// the network. Default value is infinitely.
        /// </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="MessageTemplateTextFormatter"/>.
        /// </param>
        /// <param name="httpClient">
        /// A custom <see cref="IHttpClient"/> implementation. Default value is
        /// <see cref="DefaultLokiHttpClient"/>.
        /// </param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        public static LoggerConfiguration DurableGrafanaLokiUsingFileSizeRolledBuffers(
            this LoggerSinkConfiguration sinkConfiguration,
            string uri,
            string bufferBaseFileName              = "Buffer",
            long?bufferFileSizeLimitBytes          = 1024 * 1024 * 1024,
            bool bufferFileShared                  = false,
            int?retainedBufferFileCountLimit       = 31,
            IEnumerable <LokiLabel> labels         = null,
            IEnumerable <string> excludedLabels    = null,
            LokiCredentials credentials            = null,
            string outputTemplate                  = DefaultOutputTemplate,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit                  = 1000,
            int?queueLimit  = null,
            TimeSpan?period = null,
            ITextFormatter textFormatter = null,
            IHttpClient httpClient       = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }

            var(batchFormatter, formatter, client) =
                SetupClientAndFormatters(labels, excludedLabels, textFormatter, outputTemplate, httpClient, credentials);

            return(sinkConfiguration.DurableHttpUsingFileSizeRolledBuffers(
                       LokiRoutesBuilder.BuildLogsEntriesRoute(uri),
                       bufferBaseFileName,
                       bufferFileSizeLimitBytes,
                       bufferFileShared,
                       retainedBufferFileCountLimit,
                       batchPostingLimit,
                       period,
                       formatter,
                       batchFormatter,
                       restrictedToMinimumLevel,
                       client));
        }
        /// <summary>
        /// Adds a sink that sends log events via email.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="connectionInfo">The connection info used for </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>
        /// <param name="mailSubject">The subject used in error mails</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,
            EmailConnectionInfo connectionInfo,
            string outputTemplate = DefaultOutputTemplate,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit          = EmailSink.DefaultBatchPostingLimit,
            TimeSpan?period                = null,
            IFormatProvider formatProvider = null,
            string mailSubject             = EmailConnectionInfo.DefaultSubject)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException("connectionInfo");
            }

            var defaultedPeriod = period ?? EmailSink.DefaultPeriod;
            var formatter       = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(loggerConfiguration.Sink(
                       new EmailSink(connectionInfo, batchPostingLimit, defaultedPeriod, formatter),
                       restrictedToMinimumLevel));
        }
Beispiel #15
0
        /// <summary>
        /// Adds a sink that writes log events as records in the 'LogEventEntity' Azure Table Storage table in the given storage account.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="connectionString">The Cloud Storage Account connection string to use to insert the log entries to.</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="storageTableName">Table name that log entries will be written to. Note: Optional, setting this may impact performance</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 AzureTableStorage(
            this LoggerSinkConfiguration loggerConfiguration,
            string connectionString,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            IFormatProvider formatProvider         = null,
            string storageTableName = null,
            bool writeInBatches     = false,
            TimeSpan?period         = null,
            int?batchPostingLimit   = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException("loggerConfiguration");
            }
            if (String.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException("connectionString");
            }
            var storageAccount = CloudStorageAccount.Parse(connectionString);

            return(AzureTableStorage(loggerConfiguration, storageAccount, restrictedToMinimumLevel, formatProvider, storageTableName, writeInBatches, period, batchPostingLimit));
        }
        /// <summary>
        /// Adds a sink that sends log events using HTTP POST over the network.
        /// </summary>
        /// <param name="sinkConfiguration">The logger configuration.</param>
        /// <param name="authToken">The token for your logzio account.</param>
        /// <param name="type">Your log type - it helps classify the logs you send.</param>
        /// <param name="options">Logzio configuration options</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        public static LoggerConfiguration LogzIo(
            this LoggerSinkConfiguration sinkConfiguration,
            string authToken,
            string type,
            LogzioOptions options = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }

            var client = new HttpClientWrapper();
            var sink   = new LogzioSink(
                client,
                authToken,
                type,
                options?.BatchPostingLimit ?? LogzioSink.DefaultBatchPostingLimit,
                options?.Period ?? LogzioSink.DefaultPeriod,
                options?.UseHttps ?? true);

            return(sinkConfiguration.Sink(sink, options?.RestrictedToMinimumLevel ?? LogEventLevel.Verbose));
        }
        static LoggerConfiguration RegisterSink(LoggerSinkConfiguration loggerConfiguration, KafkaClientConfiguration clientConfiguration, KafkaSinkConfiguration sinkConfiguration)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException("loggerConfiguration");
            }
            if (string.IsNullOrEmpty(clientConfiguration.ProducerConfig.BootstrapServers))
            {
                throw new ArgumentException("BootstrapServers不能为空, 至少指定一个主机名", "BootstrapServers");
            }

            sinkConfiguration.BatchPostingLimit = (sinkConfiguration.BatchPostingLimit == default) ? DefaultBatchPostingLimit : sinkConfiguration.BatchPostingLimit;
            sinkConfiguration.Period            = (sinkConfiguration.Period == default) ? DefaultPeriod : sinkConfiguration.Period;
            if (string.IsNullOrEmpty(clientConfiguration.Topic))
            {
                clientConfiguration.Topic = DefaultTopic;
            }

            return
                (loggerConfiguration
                 .Sink(new KafkaSink(clientConfiguration, sinkConfiguration), sinkConfiguration.RestrictedToMinimumLevel));
        }
        /// <summary>
        /// AWSSeriLogger target that is called when the customer is using
        /// Serilog.Settings.Configuration to set the SeriLogger configuration
        /// using a Json input.
        /// </summary>
        /// <param name="loggerConfiguration"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static LoggerConfiguration AWSSeriLog(
            this LoggerSinkConfiguration loggerConfiguration,
            IConfiguration configuration,
            IFormatProvider iFormatProvider = null,
            ITextFormatter textFormatter    = null)
        {
            AWSLoggerConfig config = new AWSLoggerConfig();

            config.LogGroup = configuration[LOG_GROUP];
            if (configuration[REGION] != null)
            {
                config.Region = configuration[REGION];
            }
            if (configuration[PROFILE] != null)
            {
                config.Profile = configuration[PROFILE];
            }
            if (configuration[BATCH_PUSH_INTERVAL] != null)
            {
                config.BatchPushInterval = TimeSpan.FromMilliseconds(Int32.Parse(configuration[BATCH_PUSH_INTERVAL]));
            }
            if (configuration[BATCH_PUSH_SIZE_IN_BYTES] != null)
            {
                config.BatchSizeInBytes = Int32.Parse(configuration[BATCH_PUSH_SIZE_IN_BYTES]);
            }
            if (configuration[MAX_QUEUED_MESSAGES] != null)
            {
                config.MaxQueuedMessages = Int32.Parse(configuration[MAX_QUEUED_MESSAGES]);
            }
            if (configuration[LOG_STREAM_NAME_SUFFIX] != null)
            {
                config.LogStreamNameSuffix = configuration[LOG_STREAM_NAME_SUFFIX];
            }
            if (configuration[LIBRARY_LOG_FILE_NAME] != null)
            {
                config.LibraryLogFileName = configuration[LIBRARY_LOG_FILE_NAME];
            }
            return(AWSSeriLog(loggerConfiguration, config, iFormatProvider, textFormatter));
        }
Beispiel #19
0
        /// <summary>
        /// <see cref="LoggerSinkConfiguration"/> extension that provides configuration chaining.
        /// </summary>
        /// <param name="loggerSinkConfiguration">Instance of <see cref="LoggerSinkConfiguration"/> object.</param>
        /// <param name="microsoftTeamsSinkOptions">The microsoft teams sink options object.</param>
        /// <param name="restrictedToMinimumLevel"><see cref="LogEventLevel"/> value that specifies minimum logging
        /// level that will be allowed to be logged.</param>
        /// <returns>Instance of <see cref="LoggerConfiguration"/> object.</returns>
        public static LoggerConfiguration MicrosoftTeams(
            this LoggerSinkConfiguration loggerSinkConfiguration,
            MicrosoftTeamsSinkOptions microsoftTeamsSinkOptions,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
        {
            if (loggerSinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerSinkConfiguration));
            }

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

            if (string.IsNullOrWhiteSpace(microsoftTeamsSinkOptions.WebHookUri))
            {
                throw new ArgumentNullException(nameof(microsoftTeamsSinkOptions.WebHookUri));
            }

            return(loggerSinkConfiguration.Sink(new MicrosoftTeamsSink(microsoftTeamsSinkOptions), restrictedToMinimumLevel));
        }
Beispiel #20
0
        /// <summary>
        /// Writes log events to InfluxDB.
        /// </summary>
        public static LoggerConfiguration InfluxDBv2(
            this LoggerSinkConfiguration loggerConfiguration,
            string source,
            string address,
            string bucket,
            string token,
            string organization = InfluxDBv2Defaults.DefaultOrganizationName,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit          = InfluxDBv2Sink.DefaultBatchPostingLimit,
            TimeSpan?period                = null,
            IFormatProvider formatProvider = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (string.IsNullOrEmpty(source))
            {
                throw new ArgumentException("source");
            }
            if (string.IsNullOrEmpty(address))
            {
                throw new ArgumentNullException(nameof(address));
            }
            if (string.IsNullOrEmpty(bucket))
            {
                throw new ArgumentException("bucket");
            }
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentException("token");
            }

            return(InfluxDBv2(
                       loggerConfiguration, source, address,
                       bucket, null, null, token,
                       organization, restrictedToMinimumLevel,
                       batchPostingLimit, period, formatProvider));
        }
Beispiel #21
0
        /// <summary>
        /// Adds a sink that writes log events as records in Azure Blob Storage blob (default name 'log.txt') with authentictaion using Azure Identity
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="formatter">Use a Serilog ITextFormatter such as CompactJsonFormatter to store object in data column of Azure blob</param>
        /// <param name="storageAccountUri">The Cloud Storage Account Uri to use to authentcate using Azure Identity</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="storageContainerName">Container where the log entries will be written to.</param>
        /// <param name="storageFileName">File name that log entries will be written to.</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>
        /// <param name="bypassBlobCreationValidation">Bypass the exception in case the blob creation fails.</param>
        /// <param name="cloudBlobProvider">Cloud blob provider to get current log blob.</param>
        /// <param name="blobSizeLimitBytes">The maximum file size to allow before a new one is rolled, expressed in bytes.</param>
        /// <param name="retainedBlobCountLimit">The number of latest blobs to be retained in the container always. Deletes older blobs when this limit is crossed.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration AzureBlobStorage(
            this LoggerSinkConfiguration loggerConfiguration,
            ITextFormatter formatter,
            Uri storageAccountUri,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string storageContainerName            = null,
            string storageFileName               = null,
            bool writeInBatches                  = false,
            TimeSpan?period                      = null,
            int?batchPostingLimit                = null,
            bool bypassBlobCreationValidation    = false,
            ICloudBlobProvider cloudBlobProvider = null,
            long?blobSizeLimitBytes              = null,
            int?retainedBlobCountLimit           = null
            )
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            try
            {
                var blobServiceClient = new BlobServiceClient(storageAccountUri, new DefaultAzureCredential());

                return(AzureBlobStorage(loggerConfiguration, formatter, blobServiceClient, restrictedToMinimumLevel, storageContainerName, storageFileName, writeInBatches, period, batchPostingLimit, bypassBlobCreationValidation, cloudBlobProvider, blobSizeLimitBytes, retainedBlobCountLimit));
            }
            catch (Exception ex)
            {
                Debugging.SelfLog.WriteLine($"Error configuring AzureBlobStorage: {ex}");

                ILogEventSink sink = new LoggerConfiguration().CreateLogger();
                return(loggerConfiguration.Sink(sink, restrictedToMinimumLevel));
            }
        }
Beispiel #22
0
        /// <summary>
        /// Writes log events to <see cref="System.Console"/>.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="formatter">Controls the rendering of log events into text, for example to log JSON. To
        /// control plain text formatting, use the overload that accepts an output template.</param>
        /// <param name="syncRoot">An object that will be used to `lock` (sync) access to the console output. If you specify this, you
        /// will have the ability to lock on this object, and guarantee that the console sink will not be about to output anything while
        /// the lock is held.</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="standardErrorFromLevel">Specifies the level at which events will be written to standard error.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public static LoggerConfiguration Konsole(
            this LoggerSinkConfiguration sinkConfiguration,
            ITextFormatter formatter,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            LoggingLevelSwitch levelSwitch         = null,
            LogEventLevel?standardErrorFromLevel   = null,
            object syncRoot = null,
            ConcurrentWriter concurrentWriter = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            concurrentWriter ??= new Window(Window.OpenBox("Logs")).Concurrent();
            syncRoot ??= DefaultSyncRoot;
            return(sinkConfiguration.Sink(new KonsoleSink(KonsoleTheme.None, formatter, standardErrorFromLevel, syncRoot, concurrentWriter), restrictedToMinimumLevel, levelSwitch));
        }
        /// <summary>
        /// <see cref="LoggerSinkConfiguration"/> extension that provides configuration chaining.
        /// <example>
        ///     new LoggerConfiguration()
        ///         .MinimumLevel.Verbose()
        ///         .WriteTo.Slack("webHookUrl", "channel" ,"username", "icon")
        ///         .CreateLogger();
        /// </example>
        /// </summary>
        /// <param name="loggerSinkConfiguration">Instance of <see cref="LoggerSinkConfiguration"/> object.</param>
        /// <param name="slackSinkOptions">The slack sink options object.</param>
        /// <param name="restrictedToMinimumLevel"><see cref="LogEventLevel"/> value that specifies minimum logging level that will be allowed to be logged.</param>
        /// <returns>Instance of <see cref="LoggerConfiguration"/> object.</returns>
        public static LoggerConfiguration Slack(
            this LoggerSinkConfiguration loggerSinkConfiguration,
            SlackSinkOptions slackSinkOptions,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
        {
            if (loggerSinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerSinkConfiguration));
            }

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

            if (string.IsNullOrWhiteSpace(slackSinkOptions.WebHookUrl))
            {
                throw new ArgumentNullException(nameof(slackSinkOptions.WebHookUrl));
            }

            return(loggerSinkConfiguration.Sink(new SlackSink(slackSinkOptions), restrictedToMinimumLevel));
        }
Beispiel #24
0
        /// <summary>
        /// 根据指定的日志属性值(字符串类型)动态生成日志Sink
        /// </summary>
        /// <param name="loggerSinkConfiguration">Sink配置</param>
        /// <param name="keyPropertyName">日志属性名称</param>
        /// <param name="defaultKey">日志属性不存在时所使用的默认值</param>
        /// <param name="configure">根据key生成目标Sink的配置委托</param>
        /// <param name="disposeCondition">Sink符合此条件时自动Dispose</param>
        /// <param name="checkInternal">Sink Dispose条件的检查间隔</param>
        /// <param name="sinkMapCountLimit">Map后目标Sink的最大数量,如果为0,立即Dispose,如果为null不Dispose,否则保留此数量的Sink</param>
        /// <param name="restrictedToMinimumLevel">重定向最小日志层级</param>
        /// <param name="levelSwitch">可动态修改的最小日志层级</param>
        /// <returns></returns>
        public static LoggerConfiguration MapCondition(
            this LoggerSinkConfiguration loggerSinkConfiguration,
            string keyPropertyName,
            string defaultKey,
            Action <string, LoggerSinkConfiguration> configure,
            Func <string, bool> disposeCondition,
            TimeSpan?checkInternal = null,
            int?sinkMapCountLimit  = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            LoggingLevelSwitch levelSwitch         = null)
        {
            return(MapCondition(loggerSinkConfiguration, le =>
            {
                if (le.Properties.TryGetValue(keyPropertyName, out var v) &&
                    v is ScalarValue sv)
                {
                    return sv.Value?.ToString() ?? defaultKey;
                }

                return defaultKey;
            }, configure, disposeCondition, checkInternal, sinkMapCountLimit, restrictedToMinimumLevel, levelSwitch));
        }
        /// <summary>
        /// Adds the WriteTo.SumoLogic() extension method to <see cref="LoggerConfiguration"/>.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration</param>
        /// <param name="textFormatter">Supplies formatting information</param>
        /// <param name="endpointUrl">Sumo Logic endpoint URL to send logs to</param>
        /// <param name="sourceName">Sumo Logic source name</param>
        /// <param name="sourceCategory">Sumo Logic source category</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="batchSizeLimit">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>

        public static LoggerConfiguration SumoLogic(
            this LoggerSinkConfiguration loggerConfiguration,
            ITextFormatter textFormatter,
            string endpointUrl,
            string sourceName     = SumoLogicSink.DefaultSourceName,
            string sourceCategory = SumoLogicSink.DefaultSourceCategory,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchSizeLimit = SumoLogicSink.DefaultBatchSizeLimit,
            TimeSpan?period    = null
            )
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }

            if (string.IsNullOrEmpty(endpointUrl))
            {
                throw new ArgumentNullException(nameof(endpointUrl));
            }

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

            var defaultPeriod = period ?? SumoLogicSink.DefaultPeriod;
            var formatter     = textFormatter;

            var sink = new SumoLogicSink(
                endpointUrl,
                sourceName,
                sourceCategory,
                formatter,
                batchSizeLimit,
                defaultPeriod);

            return(loggerConfiguration.Sink(sink, restrictedToMinimumLevel));
        }
Beispiel #26
0
        /// <summary>
        /// Adds a sink that writes log events as records in Azure Blob Storage blob (default name 'log.txt') using the given
        /// storage account connection string.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="formatter">Use a Serilog ITextFormatter such as CompactJsonFormatter to store object in data column of Azure blob</param>
        /// <param name="connectionString">The Cloud Storage Account connection string to use to insert the log entries to.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="storageContainerName">Container where the log entries will be written to.</param>
        /// <param name="storageFileName">File name that log entries will be written to.</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>
        /// <param name="bypassBlobCreationValidation">Bypass the exception in case the blob creation fails.</param>
        /// <param name="cloudBlobProvider">Cloud blob provider to get current log blob.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration AzureBlobStorage(
            this LoggerSinkConfiguration loggerConfiguration,
            ITextFormatter formatter,
            string connectionString,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string storageContainerName            = null,
            string storageFileName               = null,
            bool writeInBatches                  = false,
            TimeSpan?period                      = null,
            int?batchPostingLimit                = null,
            bool bypassBlobCreationValidation    = false,
            ICloudBlobProvider cloudBlobProvider = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException(nameof(connectionString));
            }

            try
            {
                var storageAccount = CloudStorageAccount.Parse(connectionString);
                return(AzureBlobStorage(loggerConfiguration, formatter, storageAccount, restrictedToMinimumLevel, storageContainerName, storageFileName, writeInBatches, period, batchPostingLimit, bypassBlobCreationValidation, cloudBlobProvider));
            }
            catch (Exception ex)
            {
                Debugging.SelfLog.WriteLine($"Error configuring AzureBlobStorage: {ex}");

                ILogEventSink sink = new LoggerConfiguration().CreateLogger();
                return(loggerConfiguration.Sink(sink, restrictedToMinimumLevel));
            }
        }
Beispiel #27
0
        /// <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));
        }
Beispiel #28
0
        /// <summary>
        /// Adds a sink that writes log events to a channel in Slack.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="channels">List of Slack channels.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="formatProvider">FormatProvider to apply in <see cref="LogEvent.RenderMessage(IFormatProvider)"/>. It overrides default behaviour.</param>
        /// <param name="username">Optional bot name</param>
        /// <param name="iconUrl">Optional URL to an image to use as the icon for this message.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration VerboseSlack(
            this LoggerSinkConfiguration loggerConfiguration,
            SlackChannelCollection channels,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            IFormatProvider formatProvider         = null,
            string username = null,
            string iconUrl  = null
            )
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }

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

            if (channels.Count == 0)
            {
                throw new ArgumentException("Must have at least one Slack channel defined.");
            }

            return
                (loggerConfiguration
                 .Sink
                 (
                     new SlackSink
                     (
                         channels,
                         new SlackVerboseRenderer(formatProvider).Render,
                         formatProvider,
                         username,
                         iconUrl
                     ),
                     restrictedToMinimumLevel
                 ));
        }
Beispiel #29
0
        /// <summary>
        /// Write log events to the provided <see cref="System.IO.TextWriter"/>.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="textWriter">The text writer to write log events to.</param>
        /// <param name="outputTemplate">Message template describing the output format.</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>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static LoggerConfiguration Memory(
            this LoggerSinkConfiguration sinkConfiguration,
            TextWriter textWriter,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate          = DefaultOutputTemplate,
            IFormatProvider formatProvider = null,
            LoggingLevelSwitch levelSwitch = null)
        {
            if (textWriter == null)
            {
                throw new ArgumentNullException(nameof(textWriter));
            }
            if (outputTemplate == null)
            {
                throw new ArgumentNullException(nameof(outputTemplate));
            }

            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
            var sink      = new MemorySink(textWriter, formatter);

            return(sinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch));
        }
        static LoggerConfiguration RegisterSink(
            LoggerSinkConfiguration loggerConfiguration,
            HubProxy proxy,
            SignalRSinkConfiguration signalRSinkConfiguration)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (string.IsNullOrEmpty(proxy.Uri))
            {
                throw new ArgumentException("uri cannot be 'null' or and empty string.");
            }

            signalRSinkConfiguration.BatchPostingLimit = (signalRSinkConfiguration.BatchPostingLimit == default) ? DefaultBatchPostingLimit : signalRSinkConfiguration.BatchPostingLimit;
            signalRSinkConfiguration.Period            = (signalRSinkConfiguration.Period == default) ? DefaultPeriod : signalRSinkConfiguration.Period;

            return
                (loggerConfiguration
                 .Sink(new SignalRSink(
                           signalRSinkConfiguration, proxy), signalRSinkConfiguration.RestrictedToMinimumLevel));
        }