Example #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BindingRichTextBox"/> class.
 /// </summary>
 public BindingRichTextBox()
 {
     _textFormatter = new RtfFormatter();
     Loaded += RichTextBox_Loaded;
     AddHandler(Hyperlink.RequestNavigateEvent, new RequestNavigateEventHandler(RequestNavigateHandler));
     //AddHandler(Button.ClickEvent, xxx);
 }
Example #2
0
 public override string Format(IPostParsingContext context, ITextFormatter<IPostParsingContext> formatter)
 {
     if(this.Name.ToLower() == "q" || this.Name.ToLower() == "quote") {
         return "";
     } else if(this.Name.ToLower() == "code") {
         return "[code]" + this.InnerBBCode + "[/code]";
     } else {
         string name = this.Name;
         if(name.ToLower() == "uploadimage") name = "uploadLink";
         var sb = new StringBuilder();
         sb.Append("[");
         sb.Append(name);
         if(this.Default != null && this.Default != "") {
             sb.Append("='");
             sb.Append(this.Default.Replace("'", "''"));
             sb.Append("'");
         } else {
             foreach(var attribute in this.Attributes) {
                 sb.Append(" ");
                 sb.Append(attribute.Key);
                 sb.Append("='");
                 sb.Append(attribute.Value.Replace("'", "''"));
                 sb.Append("'");
             }
         }
         sb.Append("]");
         if(this.RequireClosingTag) {
             sb.Append(this.GetInnerHTML(context, formatter));
             sb.Append("[/");
             sb.Append(name);
             sb.Append("]");
         }
         return sb.ToString();
     }
 }
        public string CompositeIdMap(IList<Column> columns, ITextFormatter formatter)
        {
            var builder = new StringBuilder();

            switch (_language)
            {
                case Language.CSharp:
                    builder.AppendLine("ComposedId(compId =>");
                    builder.AppendLine("\t\t\t\t{");
                    foreach (var column in columns)
                    {
                        builder.AppendLine("\t\t\t\t\tcompId.Property(x => x." + formatter.FormatText(column.Name) + ", m => m.Column(\"" + column.Name + "\"));");
                    }
                    builder.Append("\t\t\t\t});");
                    break;
                case Language.VB:
                    builder.AppendLine("ComposedId(Sub(compId)");
                    foreach (var column in columns)
                    {
                        builder.AppendLine("\t\t\t\t\tcompId.Property(Function(x) x." + formatter.FormatText(column.Name) + ", Sub(m) m.Column(\"" + column.Name + "\"))");
                    }
                    builder.AppendLine("\t\t\t\tEnd Sub)");
                    break;
            }

            return builder.ToString();
        }
Example #4
0
 public FileSink(string path, ITextFormatter textFormatter)
 {
     if (path == null) throw new ArgumentNullException("path");
     if (textFormatter == null) throw new ArgumentNullException("textFormatter");
     _textFormatter = textFormatter;
     _output = new StreamWriter(System.IO.File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read));
 }
        /// <summary>
        /// Adds a sink that lets you push log messages to RabbitMq
        /// </summary>
        public static LoggerConfiguration RabbitMQ(
            this LoggerSinkConfiguration loggerConfiguration,
            RabbitMQConfiguration rabbitMqConfiguration,
            ITextFormatter formatter,
            IFormatProvider formatProvider = null)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
            if (rabbitMqConfiguration == null) throw new ArgumentNullException("rabbitMqConfiguration");

            // calls overloaded extension method
            return loggerConfiguration.RabbitMQ(
                rabbitMqConfiguration.Hostname,
                rabbitMqConfiguration.Username,
                rabbitMqConfiguration.Password,
                rabbitMqConfiguration.Exchange,
                rabbitMqConfiguration.ExchangeType,
                rabbitMqConfiguration.Queue,
                rabbitMqConfiguration.DeliveryMode,
                rabbitMqConfiguration.RouteKey,
                rabbitMqConfiguration.Port,
                rabbitMqConfiguration.VHost,
                rabbitMqConfiguration.Heartbeat,
                rabbitMqConfiguration.Protocol,
                formatter,
                formatProvider);
        }
 public OutputSink(Func<IOutput> outputProvider, ITextFormatter textFormatter, Func<IOutputLogFilter> outputLogFilterProvider = null)
 {
     if (textFormatter == null) throw new ArgumentNullException("textFormatter");
     _textFormatter = textFormatter;
     _outputProvider = outputProvider;
     _outputLogFilterProvider = outputLogFilterProvider;
 }
        public XUnitTestOutputSink(ITestOutputHelper testOutputHelper, ITextFormatter textFormatter)
        {
            if (testOutputHelper == null) throw new ArgumentNullException("testOutputHelper");
            if (textFormatter == null) throw new ArgumentNullException("textFormatter");

            _output = testOutputHelper;
            _textFormatter = textFormatter;
        }
 public static LoggerConfiguration DummyRollingFile(
     this LoggerSinkConfiguration loggerSinkConfiguration,
     ITextFormatter formatter,
     string pathFormat,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
 {
     return loggerSinkConfiguration.Sink(new DummyRollingFileSink(), restrictedToMinimumLevel);
 }
Example #9
0
 public override string Format(IPostParsingContext context, ITextFormatter<IPostParsingContext> formatter)
 {
     string inner = this.GetInnerHTML(context, formatter).TrimHtml();
     if(inner == "") return "";
     string marker = this.Default;
     if(marker == null) marker = "Quote:";
     return "<blockquote><div class=\"quotetitle\">" + marker + "</div><div class=\"quotecontent\">" + inner + "</div></blockquote>";
 }
Example #10
0
 public override string Format(IPostParsingContext context, ITextFormatter<IPostParsingContext> formatter)
 {
     var urlInfo = UrlProcessor.Process(this.InnerText);
     if (urlInfo.isLocal && urlInfo.relativeUrl.StartsWith("/user/upload/")) {
         return "<f:img><f:src>" + urlInfo.relativeUrl + "</f:src><f:alt>" + urlInfo.relativeUrl + "</f:alt></f:img>";
     } else {
         return "<a href=\"" + urlInfo.relativeUrl + "\">" + urlInfo.relativeUrl + "</a>";
     }
 }
Example #11
0
        /// <summary>
        /// Construct a sink that saves logs to the specified storage account. Properties are being send as data and the level is used as tag.
        /// </summary>
        /// <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="outputTemplate">A message template describing the format used to write to the sink.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="token">The input key as found on the Logentries website.</param>
        /// <param name="useSsl">Indicates if you want to use SSL or not.</param>
        public LogentriesSink(string outputTemplate, IFormatProvider formatProvider, string token, bool useSsl, int batchPostingLimit, TimeSpan period)
            : base(batchPostingLimit, period)
        {
            if (outputTemplate == null) throw new ArgumentNullException("outputTemplate");
            _textFormatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            _token = token;
            _useSsl = useSsl;
        }
Example #12
0
 public override string Format(IPostParsingContext context, ITextFormatter<IPostParsingContext> formatter)
 {
     var url = this.url;
     var name = this.Safe(url.title);
     if(this.Default != null) {
         name = this.GetInnerHTML(context, formatter);
     }
     return string.Format("<a href=\"{0}\">{1}</a>", url.canonical, url.title);
 }
Example #13
0
 public override string Format(IPostParsingContext context, ITextFormatter<IPostParsingContext> formatter)
 {
     var upload = dataobjects.Upload.LoadById(int.Parse(this.DefaultOrValue));
     var name = this.Safe(upload.filename);
     if(this.Default != null) {
         name = this.GetInnerHTML(context, formatter);
     }
     return "<a href=\"/Upload/Info/" + upload.id.ToString() + "/\">" + name + "</a>";
 }
 public SizeLimitedFileSink(ITextFormatter formatter, TemplatedPathRoller roller, long fileSizeLimitBytes,
     RollingLogFile rollingLogFile, Encoding encoding = null)
 {
     this.formatter = formatter;
     this.roller = roller;
     this.fileSizeLimitBytes = fileSizeLimitBytes;
     this.EnableLevelLogging = roller.PathIncludesLevel;
     this.output = OpenFileForWriting(roller.LogFileDirectory, rollingLogFile, encoding ?? Encoding.UTF8);
 }
 /// <summary>
 /// Construct a sink that saves log events to the specified EventHubClient.
 /// </summary>
 /// <param name="eventHubClient">The EventHubClient to use in this sink.</param>
 /// <param name="partitionKey">PartitionKey to group events by within the Event Hub.</param>
 /// <param name="formatter">Provides formatting for outputting log data</param>
 public AzureEventHubSink(
     EventHubClient eventHubClient,
     string partitionKey,
     ITextFormatter formatter)
 {
     _eventHubClient = eventHubClient;
     _partitionKey = partitionKey;
     _formatter = formatter;
 }
 public RabbitMQSink(RabbitMQConfiguration configuration,
     ITextFormatter formatter,
     IFormatProvider formatProvider)
     : base(configuration.BatchPostingLimit, configuration.Period)
 {
     _formatter = formatter ?? new RawFormatter();
     _formatProvider = formatProvider;
     _client = new RabbitMQClient(configuration);
 }
Example #17
0
 public override string Format(IPostParsingContext context, ITextFormatter<IPostParsingContext> formatter)
 {
     string rawUrl = this.DefaultOrValue;
     string title = null;
     if(rawUrl.ToLower() != this.InnerText.ToLower()) {
         title = this.GetInnerHTML(context, formatter);
     }
     return UrlProcessor.ProcessLink(rawUrl, title, false);
 }
        /// <summary>
        /// Construct a sink that uses datadog with the specified details.
        /// </summary>
        /// <param name="datadogConfiguration">Connection information used to construct the Datadog client.</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>
        /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
        public DatadogSink(DatadogConfiguration datadogConfiguration, int batchSizeLimit, TimeSpan period, ITextFormatter textFormatter)
            : base(batchSizeLimit, period)
        {
            if (datadogConfiguration == null) throw new ArgumentNullException("datadogConfiguration");

            _datadogConfiguration = datadogConfiguration;
            _textFormatter = textFormatter;
            _statsdUdp = new StatsdUDP(datadogConfiguration.StatsdServer, datadogConfiguration.StatsdPort);
            _statsd = new Statsd(_statsdUdp);
        }
        /// <summary>
        /// Construct a sink emailing with the specified details.
        /// </summary>
        /// <param name="connectionInfo">Connection information used to construct the SMTP client and mail messages.</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>
        /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
        public EmailSink(EmailConnectionInfo connectionInfo, int batchSizeLimit, TimeSpan period, ITextFormatter textFormatter)
            : base(batchSizeLimit, period)
        {
            if (connectionInfo == null) throw new ArgumentNullException(nameof(connectionInfo));

            _connectionInfo = connectionInfo;
            _textFormatter = textFormatter;
            _smtpClient = CreateSmtpClient();
            _smtpClient.SendCompleted += SendCompletedCallback;
        }
Example #20
0
        /// <summary>
        /// Construct a sink posting to the Windows event log, creating the specified <paramref name="source"/> if it does not exist.
        /// </summary>
        /// <param name="source">The source name by which the application is registered on the local computer. </param>
        /// <param name="logName">The name of the log the source's entries are written to. Possible values include Application, System, or a custom event log.</param>
        /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
        /// <param name="machineName">The name of the machine hosting the event log written to.</param>
        public EventLogSink(string source, string logName, ITextFormatter textFormatter, string machineName)
        {
            if (source == null) throw new ArgumentNullException("source");

            _textFormatter = textFormatter;
            _source = source;

            var sourceData = new EventSourceCreationData(source, logName) { MachineName = machineName };

            if (!System.Diagnostics.EventLog.SourceExists(source, machineName)) System.Diagnostics.EventLog.CreateEventSource(sourceData);
        }
        public LogWindowViewModel(IClipboard clipboard)
        {
            this.clipboard = clipboard;

            Logs = new ReactiveList<LogMessage>();

            textFormatter = new MessageTemplateTextFormatter("{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}", CultureInfo.InvariantCulture);
            LogObserver.SubscribeOn(RxApp.TaskpoolScheduler).Subscribe(UpdateLog);

            ClearCommand = this.CreateCommand(Clear);
            CopyCommand = this.CreateCommand(Copy);
        }
        public RabbitMQSink(
            RabbitMQConfiguration configuration,
            ITextFormatter formatter,
            IFormatProvider formatProvider
       )
        {

            // prepare client
            _client = new RabbitMQClient(configuration);
            _formatProvider = formatProvider;
            _formatter = formatter ?? new RawFormatter();
        }
        public string IdMap(Column column, ITextFormatter formatter)
        {
            var mapList = new List<string>();
            var propertyName = formatter.FormatText(column.Name);

            if (column.Name.ToLower() != propertyName.ToLower())
            {
                mapList.Add("map.Column(\"" + column.Name + "\")");
            }
            mapList.Add(column.IsIdentity ? "map.Generator(Generators.Identity)" : "map.Generator(Generators.Assigned)");

            // Outer property definition
            return FormatCode("Id", propertyName, mapList);
        }
Example #24
0
        public RollingFileSink(string pathTemplate, 
                              ITextFormatter textFormatter,
                              long? fileSizeLimitBytes,
                              int? retainedFileCountLimit)
        {
            if (pathTemplate == null) throw new ArgumentNullException("pathTemplate");
            if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0) throw new ArgumentException("Negative value provided; file size limit must be non-negative");
            if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1");

            _roller = new TemplatedPathRoller(pathTemplate);
            _textFormatter = textFormatter;
            _fileSizeLimitBytes = fileSizeLimitBytes;
            _retainedFileCountLimit = retainedFileCountLimit;
        }
Example #25
0
        /// <summary>
        /// Construct a sink emailing with the specified details.
        /// </summary>
        /// <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="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>
        /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
        public EmailSink(string fromEmail, string toEmail, string mailServer, ICredentialsByHost networkCredential, int batchSizeLimit, TimeSpan period, ITextFormatter textFormatter) 
            : base(batchSizeLimit, period)
        {
            if (fromEmail == null) throw new ArgumentNullException("fromEmail");
            if (toEmail == null) throw new ArgumentNullException("toEmail");
            if (mailServer == null) throw new ArgumentNullException("mailServer");

            _fromEmail = fromEmail;
            _toEmail = toEmail;
            _textFormatter = textFormatter;

            _smtpClient = new SmtpClient(mailServer) {Credentials = networkCredential};
            _smtpClient.SendCompleted += SendCompletedCallback;
        }
Example #26
0
        public LineProxyFactory([NotNull] ITextFormatter textFormatter, 
            [NotNull] ILineMatches lineMatches,
            [NotNull] IObservable<TextScrollInfo> textScrollObservable, 
            [NotNull] IThemeProvider themeProvider)
        {
            if (textFormatter == null) throw new ArgumentNullException(nameof(textFormatter));
            if (lineMatches == null) throw new ArgumentNullException(nameof(lineMatches));
            if (textScrollObservable == null) throw new ArgumentNullException(nameof(textScrollObservable));
            if (themeProvider == null) throw new ArgumentNullException(nameof(themeProvider));

            _textFormatter = textFormatter;
            _lineMatches = lineMatches;
            _themeProvider = themeProvider;
            _textScroll = textScrollObservable.StartWith(new TextScrollInfo(0,0));
        }
Example #27
0
        /// <summary>
        /// Construct a sink emailing with the specified details.
        /// </summary>
        /// <param name="connectionInfo">Connection information used to construct the SMTP client and mail messages.</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>
        /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
        public EmailSink(EmailConnectionInfo connectionInfo, int batchSizeLimit, TimeSpan period, ITextFormatter textFormatter)
            : base(batchSizeLimit, period)
        {
            if (connectionInfo == null) throw new ArgumentNullException("connectionInfo");

            _connectionInfo = connectionInfo;
            _textFormatter = textFormatter;
            _smtpClient = CreateSmtpClient();
            _smtpClient.SendCompleted += SendCompletedCallback;

            if (_connectionInfo.MaxNumberOfSentMailsPerHour.HasValue)
            {
                _lastMailSentTimes = new Queue<DateTime>(_connectionInfo.MaxNumberOfSentMailsPerHour.Value);
            }
        }
Example #28
0
        /// <summary>
        /// Construct a sink emailing with the specified details.
        /// </summary>
        /// <param name="connectionInfo">Connection information used to construct the SMTP client and mail messages.</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>
        /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
        public EmailSink(EmailConnectionInfo connectionInfo, int batchSizeLimit, TimeSpan period, ITextFormatter textFormatter)
            : base(batchSizeLimit, period)
        {
            if (connectionInfo == null) throw new ArgumentNullException("connectionInfo");

            _connectionInfo = connectionInfo;
            _textFormatter = textFormatter;

            _smtpClient = new SmtpClient(connectionInfo.MailServer)
            {
                Credentials = _connectionInfo.NetworkCredentials,
                Port = _connectionInfo.Port,
                EnableSsl = _connectionInfo.EnableSsl
            };
            _smtpClient.SendCompleted += SendCompletedCallback;
        }
        /// <summary>
        /// Configures Serilog logger configuration with RabbitMQ
        /// </summary>
        public static LoggerConfiguration RabbitMQ(
            this LoggerSinkConfiguration loggerConfiguration,
            string hostname,
            string username,
            string password,
            string exchange,
            string exchangeType,
            string queue,
            RabbitMQDeliveryMode deliveryMode,
            string routeKey,
            int port,
            string vHost,
            ushort heartbeat,
            IProtocol protocol,
            ITextFormatter formatter,
            IFormatProvider formatProvider = null)
        {
            // guards
            if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration");
            if (string.IsNullOrEmpty(hostname)) throw new ArgumentException("hostname cannot be 'null'. Enter a valid hostname.");
            if (string.IsNullOrEmpty(username)) throw new ArgumentException("username cannot be 'null' or and empty string.");
            if (password == null) throw new ArgumentException("password cannot be 'null'. Specify an empty string if password is empty.");
            if (string.IsNullOrEmpty(queue)) throw new ArgumentException("queue cannot be 'null'. Specify a valid queue.");
            if (port <= 0 || port > 65535) throw new ArgumentOutOfRangeException("port", "port must be in a valid range (1 and 65535)");

            // setup configuration
            var config = new RabbitMQConfiguration
            {
                Hostname = hostname,
                Username = username,
                Password = password,
                Exchange = exchange ?? string.Empty,
                ExchangeType = exchangeType ?? string.Empty,
                Queue = queue,
                DeliveryMode = deliveryMode,
                RouteKey = routeKey ?? string.Empty,
                Port = port,
                VHost = vHost ?? string.Empty,
                Protocol = protocol ?? Protocols.DefaultProtocol,
                Heartbeat = heartbeat
            };
            
            return
                loggerConfiguration
                    .Sink(new RabbitMQSink(config, formatter, formatProvider));
        }
        public SizeRollingFileSink(string pathFormat, ITextFormatter formatter, long fileSizeLimitBytes,
            TimeSpan? retainedFileDurationLimit, Encoding encoding = null)
        {
            roller = new TemplatedPathRoller(pathFormat);

            this.formatter = formatter;
            this.fileSizeLimitBytes = fileSizeLimitBytes;
            this.encoding = encoding;
            this.retainedFileDurationLimit = retainedFileDurationLimit;
            this.currentSink = GetLatestSink();

            if (AsyncOptions.SupportAsync)
            {
                this.queue = new BlockingCollection<LogEvent>(AsyncOptions.BufferSize);
                Task.Run((Action)ProcessQueue, cancelToken.Token);
            }
        }
        /// <summary>
        /// Adds a sink that writes log events as records in Azure Table Storage table (default name LogEventEntity) 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 table</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="storageQueueName">Storage queue name.</param>
        /// <param name="bypassTableCreationValidation">Bypass the exception in case the table creation fails.</param>
        /// <param name="separateQueuesByLogLevel">Flag for several queues usage by log level.</param>
        /// <param name="cloudQueueProvider">Cloud table provider to get current log table.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration AzureQueueStorage(
            this LoggerSinkConfiguration loggerConfiguration,
            ITextFormatter formatter,
            string connectionString,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string storageQueueName                = null,
            bool bypassTableCreationValidation     = false,
            bool separateQueuesByLogLevel          = false,
            ICloudQueueProvider cloudQueueProvider = 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(AzureQueueStorage(
                           loggerConfiguration,
                           formatter,
                           storageAccount,
                           restrictedToMinimumLevel,
                           storageQueueName,
                           bypassTableCreationValidation,
                           separateQueuesByLogLevel,
                           cloudQueueProvider));
            }
            catch (Exception ex)
            {
                Debugging.SelfLog.WriteLine($"Error configuring AzureQueueStorage: {ex}");

                ILogEventSink sink = new LoggerConfiguration().CreateLogger();
                return(loggerConfiguration.Sink(sink, restrictedToMinimumLevel));
            }
        }
Example #32
0
        /// <summary>
        /// Adds a sink that writes log events as documents to a capped collection in a MongoDb database.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="database">The MongoDb database where the log collection will live.</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>
        /// <param name="mongoDBJsonFormatter">Formatter to produce json for MongoDB.</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,
            IMongoDatabase database,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            long cappedMaxSizeMb                = 50,
            long?cappedMaxDocuments             = null,
            string collectionName               = MongoDBSink.DefaultCollectionName,
            int batchPostingLimit               = MongoDBSink.DefaultBatchPostingLimit,
            TimeSpan?period                     = null,
            IFormatProvider formatProvider      = null,
            ITextFormatter mongoDBJsonFormatter = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            var options = new CreateCollectionOptions()
            {
                Capped  = true,
                MaxSize = cappedMaxSizeMb * 1024 * 1024
            };

            if (cappedMaxDocuments.HasValue)
            {
                options.MaxDocuments = cappedMaxDocuments.Value;
            }

            return(loggerConfiguration.Sink(
                       new MongoDBSink(
                           database,
                           batchPostingLimit,
                           period,
                           formatProvider,
                           collectionName,
                           options,
                           mongoDBJsonFormatter),
                       restrictedToMinimumLevel));
        }
Example #33
0
        /// <summary>
        /// Creates a new instance of the sink
        /// </summary>
        /// <param name="splunkHost">The host of the Splunk instance with the Event collector configured</param>
        /// <param name="eventCollectorToken">The token to use when authenticating with the event collector</param>
        /// <param name="uriPath">Change the default endpoint of the Event Collector e.g. services/collector/event</param>
        /// <param name="batchSizeLimit">The size of the batch when sending to the event collector</param>
        /// <param name="batchIntervalInSeconds">The interval in seconds that batching should occur</param>
        /// <param name="queueLimit">Maximum number of events in the queue</param>
        /// <param name="jsonFormatter">The text formatter used to render log events into a JSON format for consumption by Splunk</param>
        /// <param name="messageHandler">The handler used to send HTTP requests</param>
        public EventCollectorSink(
            string splunkHost,
            string eventCollectorToken,
            string uriPath,
            int batchIntervalInSeconds,
            int batchSizeLimit,
            int?queueLimit,
            ITextFormatter jsonFormatter,
            HttpMessageHandler messageHandler = null)
            : base(batchSizeLimit, TimeSpan.FromSeconds(batchIntervalInSeconds), queueLimit ?? DefaultQueueLimit)
        {
            _uriPath       = uriPath;
            _splunkHost    = splunkHost;
            _jsonFormatter = jsonFormatter;

            _httpClient = messageHandler != null
                ? new EventCollectorClient(eventCollectorToken, messageHandler)
                : new EventCollectorClient(eventCollectorToken);
        }
Example #34
0
        /// <summary>
        /// Adds a sink that sends log events as UDP packages over the network.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="remoteAddress">
        /// The <see cref="IPAddress"/> of the remote host or multicast group to which the UDP
        /// client should sent the logging event.
        /// </param>
        /// <param name="remotePort">
        /// The TCP port of the remote host or multicast group to which the UDP client should sent
        /// the logging event.
        /// </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="localPort">
        /// The TCP port from which the UDP client will communicate. The default is 0 and will
        /// cause the UDP client not to bind to a local port.
        /// </param>
        /// <param name="restrictedToMinimumLevel">
        /// The minimum level for events passed through the sink. The default is
        /// <see cref="LevelAlias.Minimum"/>.
        /// </param>
        /// <param name="levelSwitch">
        /// A switch allowing the pass-through minimum level to be changed at runtime.
        /// </param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        public static LoggerConfiguration Udp(
            this LoggerSinkConfiguration sinkConfiguration,
            IPAddress remoteAddress,
            int remotePort,
            ITextFormatter formatter,
            int localPort = 0,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            LoggingLevelSwitch levelSwitch         = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }

            var client = UdpClientFactory.Create(localPort, remoteAddress);
            var sink   = new UdpSink(client, remoteAddress, remotePort, formatter);

            return(sinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch));
        }
Example #35
0
        /// <summary>
        /// Adds a sink that writes log events as records in Azure Table Storage table (default name LogEventEntity) using the given
        /// storage account name and Shared Access Signature (SAS) URL.
        /// </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 table</param>
        /// <param name="sharedAccessSignature">The storage account/table SAS key.</param>
        /// <param name="accountName">The storage account name.</param>
        /// <param name="tableEndpoint">The (optional) table endpoint. Only needed for testing.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</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>
        /// <param name="keyGenerator">The key generator used to create the PartitionKey and the RowKey for each log entry</param>
        /// <param name="cloudQueueProvider">Cloud table provider to get current log table.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration AzureQueueStorage(
            this LoggerSinkConfiguration loggerConfiguration,
            ITextFormatter formatter,
            string sharedAccessSignature,
            string accountName,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string storageQueueName = null,
            ICloudQueueProvider cloudQueueProvider = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }
            if (string.IsNullOrWhiteSpace(accountName))
            {
                throw new ArgumentNullException(nameof(accountName));
            }
            if (string.IsNullOrWhiteSpace(sharedAccessSignature))
            {
                throw new ArgumentNullException(nameof(sharedAccessSignature));
            }

            try
            {
                var credentials = new StorageCredentials(sharedAccessSignature);
                CloudStorageAccount storageAccount = new CloudStorageAccount(credentials, accountName, endpointSuffix: null, useHttps: true);


                // We set bypassTableCreationValidation to true explicitly here as the the SAS URL might not have enough permissions to query if the table exists.
                return(AzureQueueStorage(loggerConfiguration, formatter, storageAccount, restrictedToMinimumLevel, storageQueueName, true, cloudQueueProvider));
            }
            catch (Exception ex)
            {
                Debugging.SelfLog.WriteLine($"Error configuring AzureQueueStorage: {ex}");

                ILogEventSink sink = new LoggerConfiguration().CreateLogger();
                return(loggerConfiguration.Sink(sink, restrictedToMinimumLevel));
            }
        }
Example #36
0
        /// <summary>
        /// Construct a sink that saves log events to the specified EventHubClient.
        /// </summary>
        /// <param name="eventHubClient">The EventHubClient to use in this sink.</param>
        /// <param name="formatter">Provides formatting for outputting log data</param>
        /// <param name="batchSizeLimit">Default is 5 messages at a time</param>
        /// <param name="period">How often the batching should be done</param>
        /// <param name="eventDataAction">An optional action for setting extra properties on each EventData.</param>
        public AzureEventHubBatchingSink(
            EventHubClient eventHubClient,
            Action <EventData, LogEvent> eventDataAction,
            TimeSpan period,
            ITextFormatter formatter = null,
            int batchSizeLimit       = 5)
            : base(batchSizeLimit, period)
        {
            formatter = formatter ?? new ScalarValueTypeSuffixJsonFormatter(renderMessage: true);

            if (batchSizeLimit < 1 || batchSizeLimit > 100)
            {
                throw new ArgumentException("batchSizeLimit must be between 1 and 100.");
            }

            _eventHubClient  = eventHubClient;
            _formatter       = formatter;
            _eventDataAction = eventDataAction;
        }
        public TwilioSink(String username, String password, String accountSid, String fromPhoneNumber, String toPhoneNumber, ITextFormatter textFormatter)
        {
            _username   = username ?? throw new ArgumentNullException(nameof(username));
            _password   = password ?? throw new ArgumentNullException(nameof(password));
            _accountSid = accountSid;              // If accountSid is null the TwilioRestClient will automatically substitute the username
            if (String.IsNullOrWhiteSpace(fromPhoneNumber))
            {
                throw new ArgumentException("Invalid fromPhoneNumber", nameof(fromPhoneNumber));
            }
            _fromPhoneNumber = new PhoneNumber(fromPhoneNumber);
            if (String.IsNullOrWhiteSpace(toPhoneNumber))
            {
                throw new ArgumentException("Invalid toPhoneNumber", nameof(toPhoneNumber));
            }
            _toPhoneNumber = new PhoneNumber(toPhoneNumber);
            _textFormatter = textFormatter ?? throw new ArgumentNullException(nameof(textFormatter));

            TwilioClient.Init(username, password, accountSid);
        }
 /// <summary>
 /// Adds a sink that writes log events to a table in a MSSqlServer database.
 /// Create a database and execute the table creation script found here
 /// https://gist.github.com/mivano/10429656
 /// or use the autoCreateSqlTable option.
 /// </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="sinkOptions">Supplies additional settings for the sink</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="columnOptions"></param>
 /// <param name="logEventFormatter">Supplies custom formatter for the LogEvent column, or null</param>
 /// <returns>Logger configuration, allowing configuration to continue.</returns>
 /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
 public static LoggerConfiguration MSSqlServer(
     this LoggerSinkConfiguration loggerConfiguration,
     string connectionString,
     MSSqlServerSinkOptions sinkOptions,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     IFormatProvider formatProvider         = null,
     ColumnOptions columnOptions            = null,
     ITextFormatter logEventFormatter       = null) =>
 loggerConfiguration.MSSqlServerInternal(
     configSectionName: AppConfigSectionName,
     connectionString: connectionString,
     sinkOptions: sinkOptions,
     restrictedToMinimumLevel: restrictedToMinimumLevel,
     formatProvider: formatProvider,
     columnOptions: columnOptions,
     logEventFormatter: logEventFormatter,
     applySystemConfiguration: new ApplySystemConfiguration(),
     sinkFactory: new MSSqlServerSinkFactory(),
     batchingSinkFactory: new PeriodicBatchingSinkFactory());
        SetupClientAndFormatters(
            IEnumerable <LokiLabel> labels,
            IEnumerable <string> excludedLabels,
            ITextFormatter textFormatter,
            string outputTemplate,
            IHttpClient httpClient,
            LokiCredentials credentials)
        {
            var batchFormatter = new LokiBatchFormatter(labels, excludedLabels);
            var formatter      = textFormatter ?? new MessageTemplateTextFormatter(outputTemplate);
            var client         = httpClient ?? new DefaultLokiHttpClient();

            if (client is ILokiHttpClient lokiHttpClient)
            {
                lokiHttpClient.SetCredentials(credentials);
            }

            return((IBatchFormatter)batchFormatter, formatter, client);
        }
Example #40
0
        public static IHostBuilder CreateHostBuilder(LoggerMode mode, string[] args)
        {
            ITextFormatter formatter = mode switch
            {
                LoggerMode.Text => new MessageTemplateTextFormatter("{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"),
                LoggerMode.Json => new JsonFormatter(renderMessage: true),
                LoggerMode.ECS => new EcsTextFormatter(),
                _ => throw new NotSupportedException()
            };

            return(Host.CreateDefaultBuilder(args)
                   .UseSerilog((context, services, configuration) => configuration
                               .ReadFrom.Configuration(context.Configuration)
                               .ReadFrom.Services(services)
                               .Enrich.FromLogContext()
                               .WriteTo.Console(formatter: formatter))
                   .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup <Startup>(); }));
        }
    }
        /// <summary>
        /// Construct a sink emailing with the specified details.
        /// </summary>
        /// <param name="connectionInfo">Connection information used to construct the SMTP client and mail messages.</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>
        /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
        /// <param name="subjectLineFormatter">The subject line formatter.</param>
        /// <exception cref="System.ArgumentNullException">connectionInfo</exception>
        public EmailSink(EmailConnectionInfo connectionInfo, int batchSizeLimit, TimeSpan period, ITextFormatter textFormatter, ITextFormatter subjectLineFormatter)
            : base(batchSizeLimit, period)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException(nameof(connectionInfo));
            }

            _connectionInfo = connectionInfo;
            _fromAddress    = MimeKit.MailboxAddress.Parse(_connectionInfo.FromEmail);
            _toAddresses    = connectionInfo
                              .ToEmail
                              .Split(",;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                              .Select(MimeKit.MailboxAddress.Parse)
                              .ToArray();

            _textFormatter    = textFormatter;
            _subjectFormatter = subjectLineFormatter;
        }
Example #42
0
        public static LoggerAuditSinkConfiguration RabbitMq(
            this LoggerAuditSinkConfiguration configuration,
            Action <RabbitMqSinkOptions> optionsSetup,
            IConnection connection,
            ITextFormatter formatter,
            LogEventLevel restrictedToMinimumLevel        = LogEventLevel.Verbose,
            LoggingLevelSwitch levelSwitch                = null,
            TextToBinaryFormatterOptions formatterOptions = null,
            bool autoCloseConnection = true)
        {
            RabbitMqSinkOptions options = configuration.Create(optionsSetup);

            RabbitMqSink rabbitMqSink = new RabbitMqSink(options, connection, formatter,
                                                         formatterOptions, autoCloseConnection);

            configuration.Sink(rabbitMqSink, restrictedToMinimumLevel, levelSwitch);

            return(configuration);
        }
Example #43
0
        public LoggerRelayEventSink(ILoggerRelay loggerRelay, CancellationToken cancellationToken, LoggerRelayEventSinkConfigArgs loggerRelayEventSinkConfigArgs = null) : base(ThreadPriority.Highest, 100)
        {
            bool mutexCreated;
            var  outputTemplate = "{Timestamp:yyyy-MM-dd hh:mm:ss.fff} [{Level}] {SourceContext} {Message}";

            DateTime.Now.ToDebugDateText();

            this.Domain            = loggerRelay.Domain;
            this.RootPath          = Environment.ExpandEnvironmentVariables(loggerRelayEventSinkConfigArgs.RootPath);
            this.CancellationToken = cancellationToken;
            this.ID = Guid.NewGuid().ToString();

            try
            {
                mutex = Mutex.OpenExisting(string.Format(@"Global\{0}+Mutex", this.Domain));
            }
            catch
            {
                mutex = new Mutex(false, string.Format(@"Global\{0}+Mutex", this.Domain), out mutexCreated);
            }

            this.loggerRelayEventSinkConfigArgs = loggerRelayEventSinkConfigArgs;
            this.loggerRelay  = loggerRelay;
            this.formatter    = new MessageTemplateTextFormatter(outputTemplate);
            this.queuedEvents = new FixedDictionary <LoggerRelayEvent, LogEvent>(NumberExtensions.MB);

            if (loggerRelayEventSinkConfigArgs != null)
            {
                if (!loggerRelayEventSinkConfigArgs.Enabled)
                {
                    return;
                }

                captureStack = loggerRelayEventSinkConfigArgs.CaptureStack.Where(c => c.Enabled).ToDictionary(c => c.Log, c => c.Assemblies.Where(a => a.Enabled).ToDictionary(a => a.Assembly, a => a));
            }

            this.Start();

            cancellationToken.Register(() =>
            {
                this.Stopped = true;
            });
        }
 /// <summary>
 /// Adds a sink that sends log events as UDP packages over the network.
 /// </summary>
 /// <param name="sinkConfiguration">
 /// Logger sink configuration.
 /// </param>
 /// <param name="remoteAddress">
 /// The <see cref="IPAddress"/> of the remote host or multicast group to which the UDP
 /// client should sent the logging event.
 /// </param>
 /// <param name="remotePort">
 /// The TCP port of the remote host or multicast group to which the UDP client should sent
 /// the logging event.
 /// </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="localPort">
 /// The TCP port from which the UDP client will communicate. The default is 0 and will
 /// cause the UDP client not to bind to a local port.
 /// </param>
 /// <param name="restrictedToMinimumLevel">
 /// The minimum level for events passed through the sink. The default is
 /// <see cref="LevelAlias.Minimum"/>.
 /// </param>
 /// <param name="levelSwitch">
 /// A switch allowing the pass-through minimum level to be changed at runtime.
 /// </param>
 /// <returns>
 /// Logger configuration, allowing configuration to continue.
 /// </returns>
 public static LoggerConfiguration Udp(
     this LoggerSinkConfiguration sinkConfiguration,
     IPAddress remoteAddress,
     int remotePort,
     ITextFormatter formatter,
     int localPort = 0,
     LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
     LoggingLevelSwitch levelSwitch         = null)
 {
     return(Udp(
                sinkConfiguration,
                remoteAddress.ToString(),
                remotePort,
                formatter,
                localPort,
                restrictedToMinimumLevel,
                levelSwitch
                ));
 }
        public static LoggerConfiguration AzureBlobOrEventHub(
            this LoggerSinkConfiguration loggerConfiguration,
            string eventHubConnectionString,
            string eventHubName,
            int eventSizeLimitInBytes,
            BlobServiceClient blobServiceClient,
            string storageContainerName = null,
            ITextFormatter formatter    = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }

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

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

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

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

            var eventHubConnectionstringBuilder = new EventHubsConnectionStringBuilder(eventHubConnectionString)
            {
                EntityPath = eventHubName
            };

            var eventHubclient = EventHubClient.CreateFromConnectionString(eventHubConnectionstringBuilder.ToString());

            return(loggerConfiguration.Sink(new AzureBlobOrEventHubCustomSink(blobServiceClient, eventHubclient, formatter, eventSizeLimitInBytes, storageContainerName)));
        }
Example #46
0
        /// <summary>
        /// Write log events to a CustomOutput in VisualStudio.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <param name="formatter">A custom formatter to apply to the output events. This can be used with
        /// e.g. <see cref="JsonFormatter"/> to produce JSON output. To customize the text layout only, use the
        /// overload that accepts an output template instead.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public static LoggerConfiguration CustomOutput(
            this LoggerSinkConfiguration sinkConfiguration,
            Guid id,
            string title,
            ITextFormatter formatter,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            LoggingLevelSwitch levelSwitch         = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            return(sinkConfiguration.Sink(new CustomOutputPaneSink(id, title, formatter), restrictedToMinimumLevel, levelSwitch));
        }
Example #47
0
        /// <summary>
        /// Construct a sink emailing with the specified details.
        /// </summary>
        /// <param name="connectionInfo">Connection information used to construct the SMTP client and mail messages.</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>
        /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
        public EmailSink(EmailConnectionInfo connectionInfo, int batchSizeLimit, TimeSpan period, ITextFormatter textFormatter)
            : base(batchSizeLimit, period)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException("connectionInfo");
            }

            _connectionInfo = connectionInfo;
            _textFormatter  = textFormatter;

            _smtpClient = new SmtpClient(connectionInfo.MailServer)
            {
                Credentials = _connectionInfo.NetworkCredentials,
                Port        = _connectionInfo.Port,
                EnableSsl   = _connectionInfo.EnableSsl
            };
            _smtpClient.SendCompleted += SendCompletedCallback;
        }
        /// <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="batchSizeLimitBytes">
        /// The approximate maximum size, in bytes, for a single batch. The value is an
        /// approximation because only the size of the log events are considered. The extra
        /// characters added by the batch formatter, where the sequence of serialized log events
        /// are transformed into a payload, are not considered. Please make sure to accommodate for
        /// those. Default value is long.MaxValue.
        /// </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>
        /// <param name="configuration">
        /// Configuration passed to <paramref name="httpClient"/>. Parameter is either manually
        /// specified when configuring the sink in source code or automatically passed in when
        /// configuring the sink using
        /// <see href="https://www.nuget.org/packages/Serilog.Settings.Configuration">Serilog.Settings.Configuration</see>.
        /// </param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        public static LoggerConfiguration DurableHttpUsingFileSizeRolledBuffers(
            this LoggerSinkConfiguration sinkConfiguration,
            string requestUri,
            string bufferBaseFileName        = "Buffer",
            long?bufferFileSizeLimitBytes    = ByteSize.GB,
            bool bufferFileShared            = false,
            int?retainedBufferFileCountLimit = 31,
            int batchPostingLimit            = 1000,
            long batchSizeLimitBytes         = long.MaxValue,
            TimeSpan?period = null,
            ITextFormatter textFormatter           = null,
            IBatchFormatter batchFormatter         = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            IHttpClient httpClient       = null,
            IConfiguration configuration = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }

            // Default values
            period ??= TimeSpan.FromSeconds(2);
            textFormatter ??= new NormalRenderedTextFormatter();
            batchFormatter ??= new DefaultBatchFormatter();
            httpClient ??= new DefaultHttpClient();
            httpClient.Configure(configuration);

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

            return(sinkConfiguration.Sink(sink, restrictedToMinimumLevel));
        }
 public AliyunLogSink(
     ILogServiceClient logServiceClient,
     ITextFormatter formatter,
     string logstoreName = null,
     string project      = null,
     string source       = null,
     string topic        = null,
     IDictionary <string, string> logTags = null,
     int batchSizeLimit = DefaultBatchPostingLimit,
     TimeSpan period    = default) : base(batchSizeLimit, period == default ? DefaultPeriod : period)
 {
     this.logServiceClient = logServiceClient ?? throw new ArgumentNullException(nameof(logServiceClient));
     this.formatter        = formatter ?? throw new ArgumentNullException(nameof(formatter));
     this.logstoreName     = logstoreName ?? throw new ArgumentNullException(nameof(logstoreName));
     this.project          = project;
     this.source           = source ?? "127.0.0.1";
     this.topic            = topic ?? nameof(AliyunLogSink);
     this.logTags          = logTags;
 }
Example #50
0
 /// <summary>
 /// Construct a sink emailing via Amazon SimpleEmailService with the specified details.
 /// </summary>
 /// <param name="isBodyHtml"></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>
 /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
 /// <param name="client"></param>
 /// <param name="emailFrom"></param>
 /// <param name="emailTo"></param>
 /// <param name="emailSubject"></param>
 public AmazonSimpleEmailServiceSink(AmazonSimpleEmailServiceClient client,
                                     string emailFrom,
                                     string emailTo,
                                     string emailSubject,
                                     bool isBodyHtml,
                                     int batchSizeLimit,
                                     TimeSpan period,
                                     ITextFormatter textFormatter)
     : base(batchSizeLimit, period)
 {
     _client = client ?? throw new ArgumentNullException(nameof(client));
     _client.AfterResponseEvent += ClientOnAfterResponseEvent;
     _client.ExceptionEvent     += ClientOnExceptionEvent;
     _emailFrom     = emailFrom;
     _emailTo       = emailTo;
     _emailSubject  = emailSubject;
     _isBodyHtml    = isBodyHtml;
     _textFormatter = textFormatter;
 }
Example #51
0
 private static ILogEventSink CreateFileSink(
     string bufferBaseFileName,
     BufferRollingInterval bufferRollingInterval,
     long?bufferFileSizeLimitBytes,
     bool bufferFileShared,
     int?retainedBufferFileCountLimit,
     ITextFormatter textFormatter)
 {
     return(new LoggerConfiguration()
            .WriteTo.File(
                path: $"{bufferBaseFileName}-.txt",
                rollingInterval: bufferRollingInterval.ToRollingInterval(),
                fileSizeLimitBytes: bufferFileSizeLimitBytes,
                shared: bufferFileShared,
                retainedFileCountLimit: retainedBufferFileCountLimit,
                formatter: textFormatter,
                rollOnFileSizeLimit: false)
            .CreateLogger());
 }
Example #52
0
        public KafkaSink(
            string bootstrapServers,
            int batchSizeLimit,
            int period,
            SecurityProtocol securityProtocol,
            SaslMechanism saslMechanism,
            Func <LogEvent, string> topicDecider,
            string saslUsername,
            string saslPassword,
            string sslCaLocation,
            ITextFormatter formatter = null) : base(batchSizeLimit, TimeSpan.FromSeconds(period))
        {
            ConfigureKafkaConnection(bootstrapServers, securityProtocol, saslMechanism, saslUsername,
                                     saslPassword, sslCaLocation);

            this.formatter = formatter ?? new Formatting.Json.JsonFormatter(renderMessage: true);

            this._topicDecider = topicDecider;
        }
        /// <summary>
        /// A sink that puts log events into a provided Azure Event Hub.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="formatter">Formatter used to convert log events to text.</param>
        /// <param name="eventHubClient">The Event Hub 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>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration AzureEventHub(
            this LoggerAuditSinkConfiguration loggerConfiguration,
            ITextFormatter formatter,
            EventHubClient eventHubClient,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException("loggerConfiguration");
            }
            if (eventHubClient == null)
            {
                throw new ArgumentNullException("eventHubClient");
            }

            var sink = new AzureEventHubSink(eventHubClient, formatter);

            return(loggerConfiguration.Sink(sink, restrictedToMinimumLevel));
        }
Example #54
0
        /// <summary>
        /// Writes log events to <see cref="ITestOutputHelper"/>.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="testOutputHelper">The <see cref="ITestOutputHelper"/> that will be written to.</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="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public static LoggerConfiguration TestOutput(
            this LoggerSinkConfiguration sinkConfiguration,
            ITestOutputHelper testOutputHelper,
            ITextFormatter formatter,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            LoggingLevelSwitch levelSwitch         = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }

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

            return(sinkConfiguration.Sink(new TestOutputSink(testOutputHelper, formatter), restrictedToMinimumLevel, levelSwitch));
        }
Example #55
0
        public string Map(Column column, string fieldName, ITextFormatter Formatter, bool includeLengthAndScale = true)
        {
            var mappedStrBuilder = new StringBuilder(string.Format("Map(x => x.{0})", fieldName));

            mappedStrBuilder.Append(Constants.Dot);
            mappedStrBuilder.Append("Column(\"" + column.Name + "\")");

            if (!column.IsNullable)
            {
                mappedStrBuilder.Append(Constants.Dot);
                mappedStrBuilder.Append("Not.Nullable()");
            }

            if (column.IsUnique)
            {
                mappedStrBuilder.Append(Constants.Dot);
                mappedStrBuilder.Append("Unique()");
            }

            if (column.DataLength.GetValueOrDefault() > 0 & includeLengthAndScale)
            {
                mappedStrBuilder.Append(Constants.Dot);
                mappedStrBuilder.Append("Length(" + column.DataLength + ")");
            }
            else
            {
                if (column.DataPrecision.GetValueOrDefault(0) > 0 & includeLengthAndScale)
                {
                    mappedStrBuilder.Append(Constants.Dot);
                    mappedStrBuilder.Append("Precision(" + column.DataPrecision + ")");
                }

                if (column.DataScale.GetValueOrDefault(0) > 0 & includeLengthAndScale)
                {
                    mappedStrBuilder.Append(Constants.Dot);
                    mappedStrBuilder.Append("Scale(" + column.DataScale + ")");
                }
            }


            mappedStrBuilder.Append(Constants.SemiColon);
            return(mappedStrBuilder.ToString());
        }
Example #56
0
        public CustomOutputPaneSink(Guid id, string title, ITextFormatter textFormatter)
        {
            try {
                if (id == Guid.Empty)
                {
                    throw new ArgumentException(nameof(id));
                }
                if (title.IsNullOrWhiteSpace())
                {
                    throw new ArgumentNullException(nameof(title));
                }
                _textFormatter = textFormatter ?? throw new ArgumentNullException(nameof(textFormatter));
                ThreadHelper.ThrowIfNotOnUIThread();

                var outWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;
                if (outWindow == null)
                {
                    return;
                }

                outWindow.CreatePane(ref id, title, 1, 1);
                outWindow.GetPane(ref id, out _customOutputWindowPane);
                if (_customOutputWindowPane == null)
                {
                    return;
                }
#if DEBUG
                // Brings this pane into view
                _customOutputWindowPane.Activate();
#endif
            }
            catch (COMException) {
#if DEBUG
#endif
            }
            catch (Exception ex) {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(ex);
                System.Diagnostics.Debugger.Break();
#endif
            }
        }
Example #57
0
        /// <summary>
        /// Adds a sink that writes log events as records in an Azure Blob Storage blob (default LogEventEntity) using the given storage account.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="formatter">Use a Serilog ITextFormatter such as CompactJsonFormatter to store object in Azure blob</param>
        /// <param name="storageAccount">The Cloud Storage Account 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="storageFolderName">Folder name that 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,
            CloudStorageAccount storageAccount,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string storageFolderName             = 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 (storageAccount == null)
            {
                throw new ArgumentNullException(nameof(storageAccount));
            }

            ILogEventSink sink;

            try
            {
                sink = writeInBatches ?
                       (ILogEventSink) new AzureBatchingBlobStorageSink(storageAccount, formatter, batchPostingLimit ?? DefaultBatchPostingLimit, period ?? DefaultPeriod, storageFolderName, storageFileName, bypassBlobCreationValidation, cloudBlobProvider) :
                       new AzureBlobStorageSink(storageAccount, formatter, storageFolderName, storageFileName, bypassBlobCreationValidation, cloudBlobProvider);
            }
            catch (Exception ex)
            {
                Debugging.SelfLog.WriteLine($"Error configuring AzureBlobStorage: {ex}");
                sink = new LoggerConfiguration().CreateLogger();
            }

            return(loggerConfiguration.Sink(sink, restrictedToMinimumLevel));
        }
Example #58
0
        private ElasticsearchSinkState(ElasticsearchSinkOptions options)
        {
            if (string.IsNullOrWhiteSpace(options.IndexFormat))
            {
                throw new ArgumentException("options.IndexFormat");
            }
            if (string.IsNullOrWhiteSpace(options.TypeName))
            {
                throw new ArgumentException("options.TypeName");
            }
            if (string.IsNullOrWhiteSpace(options.TemplateName))
            {
                throw new ArgumentException("options.TemplateName");
            }

            _templateName        = options.TemplateName;
            _templateMatchString = IndexFormatRegex.Replace(options.IndexFormat, @"$1*$2");

            _indexDecider         = options.IndexDecider ?? ((@event, offset) => string.Format(options.IndexFormat, offset));
            _bufferedIndexDecider = options.BufferIndexDecider ?? ((@event, offset) => string.Format(options.IndexFormat, offset));

            _options = options;

            var configuration = new ConnectionConfiguration(options.ConnectionPool, options.Connection, options.Serializer)
                                .RequestTimeout(options.ConnectionTimeout);

            if (options.ModifyConnectionSettings != null)
            {
                configuration = options.ModifyConnectionSettings(configuration);
            }

            configuration.ThrowExceptions();

            _client = new ElasticLowLevelClient(configuration);

            _formatter = options.CustomFormatter ?? CreateDefaultFormatter(options);

            _durableFormatter = options.CustomDurableFormatter ?? CreateDefaultDurableFormatter(options);

            _registerTemplateOnStartup  = options.AutoRegisterTemplate;
            TemplateRegistrationSuccess = !_registerTemplateOnStartup;
        }
Example #59
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>
        /// <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,
            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,
            long?blobSizeLimitBytes              = null,
            int?retainedBlobCountLimit           = 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 blobServiceClient = new BlobServiceClient(connectionString);

                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));
            }
        }
        internal static SinkDependencies Create(
            string connectionString,
            MSSqlServerSinkOptions sinkOptions,
            IFormatProvider formatProvider,
            ColumnOptions columnOptions,
            ITextFormatter logEventFormatter)
        {
            columnOptions = columnOptions ?? new ColumnOptions();
            columnOptions.FinalizeConfigurationForSinkConstructor();

            var sqlConnectionFactory =
                new SqlConnectionFactory(connectionString,
                                         sinkOptions?.EnlistInTransaction ?? default,
                                         sinkOptions?.UseAzureManagedIdentity ?? default,
                                         new SqlConnectionStringBuilderWrapper(),
                                         new AzureManagedServiceAuthenticator(
                                             sinkOptions?.UseAzureManagedIdentity ?? default,
                                             sinkOptions.AzureServiceTokenProviderResource,
                                             sinkOptions.AzureTenantId));
            var logEventDataGenerator =
                new LogEventDataGenerator(columnOptions,
                                          new StandardColumnDataGenerator(columnOptions, formatProvider,
                                                                          new XmlPropertyFormatter(),
                                                                          logEventFormatter),
                                          new PropertiesColumnDataGenerator(columnOptions));

            var sinkDependencies = new SinkDependencies
            {
                SqlTableCreator = new SqlTableCreator(
                    sinkOptions.TableName, sinkOptions.SchemaName, columnOptions,
                    new SqlCreateTableWriter(), sqlConnectionFactory),
                DataTableCreator   = new DataTableCreator(sinkOptions.TableName, columnOptions),
                SqlBulkBatchWriter = new SqlBulkBatchWriter(
                    sinkOptions.TableName, sinkOptions.SchemaName,
                    columnOptions.DisableTriggers, sqlConnectionFactory, logEventDataGenerator),
                SqlLogEventWriter = new SqlLogEventWriter(
                    sinkOptions.TableName, sinkOptions.SchemaName,
                    sqlConnectionFactory, logEventDataGenerator)
            };

            return(sinkDependencies);
        }