コード例 #1
0
        public void AligmentAndWidthCanBeCombined()
        {
            var formatter = new MessageTemplateTextFormatter("{Level,5:w3}", CultureInfo.InvariantCulture);
            var evt       = DelegatingSink.GetLogEvent(l => l.Information("Hello"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal("  inf", sw.ToString());
        }
コード例 #2
0
        public void AppliesCustomFormatterToEnums()
        {
            var formatter = new MessageTemplateTextFormatter("{Message}", new SizeFormatter(CultureInfo.InvariantCulture));
            var evt       = DelegatingSink.GetLogEvent(l => l.Information("Size {Size}", Size.Large));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal("Size Huge", sw.ToString());
        }
コード例 #3
0
        public void FixedLengthLevelSupportsLowerCasing()
        {
            var formatter = new MessageTemplateTextFormatter("{Level:w3}", CultureInfo.InvariantCulture);
            var evt       = DelegatingSink.GetLogEvent(l => l.Information("Hello"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal("inf", sw.ToString());
        }
コード例 #4
0
        public void DefaultLevelLengthIsFullText()
        {
            var formatter = new MessageTemplateTextFormatter("{Level}", CultureInfo.InvariantCulture);
            var evt       = DelegatingSink.GetLogEvent(l => l.Information("Hello"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal("Information", sw.ToString());
        }
コード例 #5
0
        public void DoNotDuplicatePropertiesAlreadyRenderedInOutputTemplate()
        {
            var formatter = new MessageTemplateTextFormatter("{Foo} {Properties}", CultureInfo.InvariantCulture);
            var evt       = DelegatingSink.GetLogEvent(l => l.ForContext("Foo", 42).ForContext("Bar", 42).Information("Hello from bar!"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal("42 {Bar: 42}", sw.ToString());
        }
コード例 #6
0
        public NUnitSink(MessageTemplateTextFormatter formatter)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            _formatter = formatter;
        }
コード例 #7
0
        public static LoggerConfiguration MySink(this LoggerSinkConfiguration sinkConfiguration,
                                                 int queueLimit,
                                                 string outputTemplate          = DefaultConsoleOutputTemplate,
                                                 IFormatProvider formatProvider = null)
        {
            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(sinkConfiguration.Sink(new MySink(queueLimit, formatter)));
        }
コード例 #8
0
        public void LowercaseFormatSpecifierIsSupportedForStrings()
        {
            var formatter = new MessageTemplateTextFormatter("{Name:w}", CultureInfo.InvariantCulture);
            var evt       = DelegatingSink.GetLogEvent(l => l.Information("{Name}", "Nick"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal("nick", sw.ToString());
        }
コード例 #9
0
        public void AppliesJsonFormattingToPropertiesTokenWhenSpecified(string format, string expected)
        {
            var formatter = new MessageTemplateTextFormatter("{Properties" + format + "}", null);
            var evt       = DelegatingSink.GetLogEvent(l => l.ForContext("Name", "World").Information("Hello"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal(expected, sw.ToString());
        }
コード例 #10
0
        public void MessageTemplatesContainingFormatStringPropertiesRenderCorrectly()
        {
            var formatter = new MessageTemplateTextFormatter("{Message}", CultureInfo.InvariantCulture);
            var evt       = DelegatingSink.GetLogEvent(l => l.Information("{Message}", "Hello, world!"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal("\"Hello, world!\"", sw.ToString());
        }
コード例 #11
0
        public void NonMessagePropertiesAreRendered()
        {
            var formatter = new MessageTemplateTextFormatter("{Properties}", CultureInfo.InvariantCulture);
            var evt       = DelegatingSink.GetLogEvent(l => l.ForContext("Foo", 42).Information("Hello from {Bar}!", "bar"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal("{Foo: 42}", sw.ToString());
        }
コード例 #12
0
        public void AppliesJsonFormattingToMessageStructuresWhenSpecified(string format, string expected)
        {
            var formatter = new MessageTemplateTextFormatter("{Message" + format + "}", null);
            var evt       = DelegatingSink.GetLogEvent(l => l.Information("{@Obj}", new { Name = "World" }));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal(expected, sw.ToString());
        }
コード例 #13
0
        public static LoggerConfiguration NLog(
            this LoggerSinkConfiguration loggerConfiguration,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate          = DefaultOutputTemplate,
            IFormatProvider formatProvider = null)
        {
            var textFormatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(loggerConfiguration.Sink(new NLogSink(textFormatter), restrictedToMinimumLevel));
        }
コード例 #14
0
        public void UsesFormatProvider()
        {
            var french    = new CultureInfo("fr-FR");
            var formatter = new MessageTemplateTextFormatter("{Message}", french);
            var evt       = DelegatingSink.GetLogEvent(l => l.Information("{0}", 12.345));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal("12,345", sw.ToString());
        }
コード例 #15
0
        public static LoggerConfiguration Debug(this LoggerSinkConfiguration loggerConfiguration,
                                                string outputTemplate          = DefaultOutputTemplate,
                                                IFormatProvider formatProvider = null)
        {
            Guard.ArgumentNotNull(() => loggerConfiguration, loggerConfiguration);

            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(loggerConfiguration.Sink(new DebugLogSink(formatter)));
        }
        /// <summary>
        /// Write log events to a series of files. Each file will be named according to
        /// the date of the first log entry written to it. Only simple date-based rolling is
        /// currently supported.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="pathFormat">String describing the location of the log files,
        /// with {Date} in the place of the file date. E.g. "Logs\myapp-{Date}.log" will result in log
        /// files such as "Logs\myapp-2013-10-20.log", "Logs\myapp-2013-10-21.log" and so on.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="fileSizeLimitBytes">The maximum size, in bytes, to which any single log file will be allowed to grow.
        /// For unrestricted growth, pass null. The default is 1 GB.</param>
        /// <param name="retainedFileDurationLimit">The maximum timespan of log files that will be retained,
        /// including the current log file. The value should folowing TimeSpan format (d.hh.mm.ss).The default is 7 days</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        /// <remarks>The file will be written using the UTF-8 character set.</remarks>
        public static LoggerConfiguration SizeRollingFile(this LoggerSinkConfiguration sinkConfiguration, string pathFormat, TimeSpan? retainedFileDurationLimit = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, string outputTemplate = DefaultOutputTemplate,
            IFormatProvider formatProvider = null, long? fileSizeLimitBytes = null, bool supportAsync = false, int? bufferSize = null, int? maxRetries = null)
        {

            var templateFormatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return SizeRollingFile(sinkConfiguration, templateFormatter, pathFormat, retainedFileDurationLimit,
                restrictedToMinimumLevel, outputTemplate, formatProvider, fileSizeLimitBytes, supportAsync, bufferSize, maxRetries);
        }
コード例 #17
0
        /// <summary>
        /// Initialize a new instance of <see cref="Rfc3164Formatter"/> class allowing you to specify values for
        /// the facility, application name and template formatter.
        /// </summary>
        /// <param name="facility">One of the <see cref="Facility"/> values indicating the machine process that created the syslog event. Defaults to <see cref="Facility.Local0"/>.</param>
        /// <param name="applicationName">A user supplied value representing the application name that will appear in the syslog event. Must be all printable ASCII characters. Max length 32. Defaults to the current process name.</param>
        /// <param name="templateFormatter">See <see cref="Formatting.ITextFormatter"/>.</param>
        public Rfc3164Formatter(Facility facility = Facility.Local0, string applicationName = null,
                                MessageTemplateTextFormatter templateFormatter = null, ITextFormatter formatter = null)
            : base(facility, templateFormatter, formatter)
        {
            this.applicationName = applicationName ?? ProcessName;

            // Conform to the RFC
            this.applicationName = this.applicationName
                                   .AsPrintableAscii()
                                   .WithMaxLength(32);
        }
コード例 #18
0
        public static WinFormsSinkInternal MakeSimpleTextBoxSink(ITextFormatter formatter = null)
        {
            if (formatter == null)
            {
                formatter = new MessageTemplateTextFormatter("{Timestamp} [{Level}] {Message} {Exception}");
            }

            _simpleTextBoxSink = new WinFormsSinkInternal(formatter);

            return(_simpleTextBoxSink);
        }
コード例 #19
0
        /// <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="outputTemplate">A message template describing the format used to write to the sink. The default is "{Message}".</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</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,
            string outputTemplate                  = DefaultOutputTemplate,
            IFormatProvider formatProvider         = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
        {
            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(loggerSinkConfiguration.Slack(slackSinkOptions, formatter, restrictedToMinimumLevel));
        }
コード例 #20
0
        const int DefaultRetainedFileCountLimit = 31; // A long month of logs

        /// <summary>
        /// Writes log events to <see cref="System.Console"/>.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink.</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public static LoggerConfiguration Console(
            this LoggerSinkConfiguration sinkConfiguration,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate = DefaultConsoleOutputTemplate,
            IFormatProvider formatProvider = null)
        {
            if (sinkConfiguration == null) throw new ArgumentNullException("sinkConfiguration");
            if (outputTemplate == null) throw new ArgumentNullException("outputTemplate");
            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
            return sinkConfiguration.Sink(new ConsoleSink(formatter), restrictedToMinimumLevel);
        }
コード例 #21
0
        public void PaddingIsApplied(int n, string format, string expected)
        {
            var formatter = new MessageTemplateTextFormatter("{ThreadId" + format + "}", null);
            var evt       = Some.InformationEvent();

            evt.AddOrUpdateProperty(new LogEventProperty("ThreadId", new ScalarValue(n)));
            var sw = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal(expected, sw.ToString());
        }
コード例 #22
0
ファイル: SimpleTextFormatter.cs プロジェクト: GFlisch/Arc4u
        public SimpleTextFormatter()
        {
            MessageFormatter  = new MessageTemplateTextFormatter("{Message}");
            PropertyFormatter = new JsonPropertiesFormatter();

            MessageCategoryMap = Enum.GetValues(typeof(MessageCategory)).Cast <MessageCategory>()
                                 .ToDictionary(x => x, x => x.ToString());

            MessageLogLevelMap = Enum.GetValues(typeof(LogEventLevel)).Cast <LogEventLevel>()
                                 .ToDictionary(x => x, x => x.ToMessageType().ToString());
        }
コード例 #23
0
        public IYouTrackReportingConfigurationExpressions FormatDescriptionWith(string template, IFormatProvider formatProvider = null)
        {
            if (template == null)
            {
                throw new ArgumentNullException(nameof(template));
            }

            DescriptionFormatter = new MessageTemplateTextFormatter(template, formatProvider);

            return(this);
        }
コード例 #24
0
        public void Should_format_message_with_output_template()
        {
            var templateFormatter = new MessageTemplateTextFormatter("--- {Message} ---", null);
            var formatter         = new TestFormatter(templateFormatter);

            var template  = new MessageTemplateParser().Parse(MESSAGE);
            var infoEvent = new LogEvent(DateTimeOffset.Now, LogEventLevel.Information, null, template, Enumerable.Empty <LogEventProperty>());

            var formatted = formatter.FormatMessage(infoEvent);

            formatted.ShouldBe($"--- {MESSAGE} ---");
        }
コード例 #25
0
ファイル: VisualStudioSink.cs プロジェクト: Tonur/PowerClean
        public static LoggerConfiguration VisualStudio(this LoggerSinkConfiguration loggerConfiguration,
                                                       IVsOutputWindow outputWindow, LogEventLevel minimumLogEventLevel = LogEventLevel.Information, string outputTemplate = "{Message}",
                                                       IFormatProvider?formatProvider = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            var templateTextFormatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(loggerConfiguration.Sink(new VisualStudioSink(outputWindow, minimumLogEventLevel, outputTemplate, templateTextFormatter)));
        }
コード例 #26
0
        public static LoggerConfiguration RollingFileAsText(this LoggerSinkConfiguration sinkConfiguration, string pathFormat, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException("sinkConfiguration");
            }

            var formatter = new MessageTemplateTextFormatter(DefaultOutputTemplate, null);
            var sink      = new RollingFileSink(pathFormat, formatter, DefaultFileSizeLimitBytes, DefaultRetainedFileCountLimit);

            return(sinkConfiguration.Sink(sink, restrictedToMinimumLevel));
        }
コード例 #27
0
        public void AnEmptyPropertiesTokenIsAnEmptyStructureValueWithDefaultFormatting()
        {
            var formatter = new MessageTemplateTextFormatter("{Properties}", null);
            var evt       = DelegatingSink.GetLogEvent(l => l.Information("Hello"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);

            var expected = new StructureValue(Enumerable.Empty <LogEventProperty>()).ToString();

            Assert.Equal(expected, sw.ToString());
        }
コード例 #28
0
        public static LoggerConfiguration InMemoryCache(this LoggerSinkConfiguration sinkConfiguration,
                                                        string outputTemplate          = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
                                                        IFormatProvider formatProvider = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }
            var templateTextFormatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(sinkConfiguration.Sink(new InMemorySink(templateTextFormatter)));
        }
コード例 #29
0
        public void FixedLengthLevelIsSupported(
            LogEventLevel level,
            int width,
            string expected)
        {
            var formatter = new MessageTemplateTextFormatter($"{{Level:t{width}}}", CultureInfo.InvariantCulture);
            var evt       = DelegatingSink.GetLogEvent(l => l.Write(level, "Hello"));
            var sw        = new StringWriter();

            formatter.Format(evt, sw);
            Assert.Equal(expected, sw.ToString());
        }
        public void FormatLogEventMessage()
        {
            string message = "PlainMessageTemplate";

            LogEvent logEvent = LogEventHelper.GetLogEvent(message);

            ITextFormatter formatter = new MessageTemplateTextFormatter("{Message}", null);

            string formattedMessage = TraceWriterSink.FormatLogEventMessage(logEvent, formatter);

            Assert.Equal(message, formattedMessage);
        }
        /// <summary>
        ///     Write log events to a series of files. Each file will be named according to
        ///     the date of the first log entry written to it. Only simple date-based rolling is
        ///     currently supported.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="pathFormat">
        ///     String describing the location of the log files,
        ///     with {Date} in the place of the file date. E.g. "Logs\myapp-{Date}.log" will result in log
        ///     files such as "Logs\myapp-2013-10-20.log", "Logs\myapp-2013-10-21.log" and so on.
        /// </param>
        /// <param name="restrictedToMinimumLevel">
        ///     The minimum level for
        ///     events passed through the sink. Ignored when is specified.
        /// </param>
        /// <param name="outputTemplate">
        ///     A message template describing the format used to write to the sink.
        ///     the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".
        /// </param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="fileSizeLimitBytes">
        ///     The maximum size, in bytes, to which any single log file will be allowed to grow.
        ///     For unrestricted growth, pass null. The default is 1 GB.
        /// </param>
        /// <param name="retainedFileDurationLimit">
        ///     The maximum timespan of log files that will be retained,
        ///     including the current log file. The value should folowing TimeSpan format (d.hh.mm.ss).The default is 7 days
        /// </param>
        /// <param name="supportAsync">Async Write Support</param>
        /// <param name="bufferSize">Buffer Size</param>
        /// <param name="maxRetries">Max Retries</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,
                                                      TimeSpan?retainedFileDurationLimit     = null,
                                                      LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, string outputTemplate = DefaultOutputTemplate,
                                                      IFormatProvider formatProvider         = null, long?fileSizeLimitBytes = null, bool supportAsync = false,
                                                      int?bufferSize = null, int?maxRetries = null)
        {
            var templateFormatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(RollingFile(sinkConfiguration, templateFormatter, pathFormat, retainedFileDurationLimit,
                               restrictedToMinimumLevel, outputTemplate, formatProvider, fileSizeLimitBytes, supportAsync, bufferSize,
                               maxRetries));
        }