TemplateLogFormatter

Namespace: RockLib.Logging
We found 10 examples in language CSharp for this search. You will see 31 fragments of code.

            [Fact]
            public void InvokingConstructor2WithUndefinedLogLevelThrowsArgumentException()
            {
                Assert.Throws<ArgumentException>(() => new ConsoleLogProvider(new TemplateLogFormatter(""), (LogLevel)(int.MinValue)));
            }

            [Fact]
            public void InvokingConstructor2WithNegativeTimeoutThrowsArgumentException()
            {
                Assert.Throws<ArgumentException>(() => new ConsoleLogProvider(new TemplateLogFormatter(""), timeout:TimeSpan.FromSeconds(-1)));
            }

            [Fact]
            public void InvokingConstructor2WithUndefinedLogLevelThrowsArgumentException()
            {
                Assert.Throws<ArgumentException>(() => new FileLogProvider(_file, new TemplateLogFormatter(""), (LogLevel)(int.MinValue)));
            }

            [Fact]
            public void InvokingConstructor2WithNegativeTimeoutThrowsArgumentException()
            {
                Assert.Throws<ArgumentException>(() => new FileLogProvider(_file, new TemplateLogFormatter(""), timeout: TimeSpan.FromSeconds(-1)));
            }

            [Fact]
            public void InvokingConstructor2WithNullFileThrowsArgumentNullException()
            {
                Assert.Throws<ArgumentNullException>(() => new FileLogProvider(null, new TemplateLogFormatter("")));
            }

            [Fact]
            public void InvokingConstructor2WithUndefinedLogLevelThrowsArgumentException()
            {
                Assert.Throws<ArgumentException>(() => new RollingFileLogProvider(_file, new TemplateLogFormatter(""), (LogLevel)(int.MinValue)));
            }

        [Fact]
        public void Constructor1SetsFormatterToTemplateLogFormatter()
        {
            var debugLogProvider = new DebugLogProvider("foo");

            debugLogProvider.Formatter.Should().BeOfType<TemplateLogFormatter>();
            var formatter = (TemplateLogFormatter)debugLogProvider.Formatter;
            formatter.Template.Should().Be("foo");
        }

        [Fact]
        public void Constructor1SetsFormatterToTemplateLogFormatter()
        {
            var consoleLogProvider = new ConsoleLogProvider("foo");

            consoleLogProvider.Formatter.Should().BeOfType<TemplateLogFormatter>();
            var formatter = (TemplateLogFormatter)consoleLogProvider.Formatter;
            formatter.Template.Should().Be("foo");
        }


        [Fact]
        public void Constructor1SetsFormatterToTemplateLogFormatter()
        {
            var fileLogProvider = new FileLogProvider(_file, "foo");

            fileLogProvider.Formatter.Should().BeOfType<TemplateLogFormatter>();
            var formatter = (TemplateLogFormatter)fileLogProvider.Formatter;
            formatter.Template.Should().Be("foo");
        }


        [Fact]
        public void Constructor1SetsFormatterToTemplateLogFormatter()
        {
            var fileLogProvider = new RollingFileLogProvider(_logFilePath, "foo");

            fileLogProvider.Formatter.Should().BeOfType<TemplateLogFormatter>();
            var formatter = (TemplateLogFormatter)fileLogProvider.Formatter;
            formatter.Template.Should().Be("foo");
        }


        /// <summary>
        /// Formats the log entry using the <see cref="Formatter"/> property and writes it to standard out.
        /// </summary>
        /// <param name="logEntry">The log entry to write.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
        /// <returns>A task that completes when the log entry has been written to standard out.</returns>
        public Task WriteAsync(LogEntry logEntry, CancellationToken cancellationToken = default)
        {
            var formattedLog = Formatter.Format(logEntry);
            return _consoleWriter.WriteLineAsync(formattedLog);
        }


        /// <summary>
        /// Formats the log entry using the <see cref="Formatter"/> property and writes it the file
        /// specified by the <see cref="File"/> property.
        /// </summary>
        /// <param name="logEntry">The log entry to write.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
        /// <returns>A task that completes when the log entry has been written to file.</returns>
        public async Task WriteAsync(LogEntry logEntry, CancellationToken cancellationToken = default)
        {
            var formattedLogEntry = Formatter.Format(logEntry);

            await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                await SynchronizedWriteAsync(formattedLogEntry, cancellationToken).ConfigureAwait(false);
            }
            finally
            {
                _semaphore.Release();
            }
        }

        /// <summary>
        /// Writes a formatted log entry to the file. This method is synchronized, that is,
        /// only one thread will execute this method at any given time.
        /// </summary>
        /// <param name="formattedLogEntry">The formatted log entry.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
        /// <returns>A task that represents the asynchronous write operation.</returns>
        protected virtual async Task SynchronizedWriteAsync(string formattedLogEntry, CancellationToken cancellationToken)
        {
            using (var writer = new StreamWriter(File, true))
            {
                await writer.WriteLineAsync(formattedLogEntry).ConfigureAwait(false);
            }
        }


        [Fact(DisplayName = "AddLogProvider method adds log provider of specified type")]
        public void AddLogProviderMethodHappyPath()
        {
            var builder = new TestLoggerBuilder();

            IDependency dependency = new ConcreteDependency();
            int setting = 123;

            var serviceProvider = new ServiceCollection()
                .AddSingleton(dependency)
                .BuildServiceProvider();

            builder.AddLogProvider<TestLogProvider>(setting);

            var registration =
                builder.LogProviderRegistrations.Should().ContainSingle()
                .Subject;

            var logProvider = registration.Invoke(serviceProvider);

            var testLogProvider =
                logProvider.Should().BeOfType<TestLogProvider>()
                .Subject;
            testLogProvider.Setting.Should().Be(setting);
            testLogProvider.Dependency.Should().BeSameAs(dependency);
        }

        [Fact(DisplayName = "AddLogProvider method throws when builder parameter is null")]
        public void AddLogProviderMethodSadPath()
        {
            ILoggerBuilder builder = null;

            Action act = () => builder.AddLogProvider<TestLogProvider>();

            act.Should().ThrowExactly<ArgumentNullException>().WithMessage("*builder*");
        }

        [Fact(DisplayName = "AddContextProvider method adds context provider of specified type")]
        public void AddContextProviderMethodHappyPath()
        {
            var builder = new TestLoggerBuilder();

            IDependency dependency = new ConcreteDependency();
            int setting = 123;

            var serviceProvider = new ServiceCollection()
                .AddSingleton(dependency)
                .BuildServiceProvider();

            builder.AddContextProvider<TestContextProvider>(setting);

            var registration =
                builder.ContextProviderRegistrations.Should().ContainSingle()
                .Subject;

            var contextProvider = registration.Invoke(serviceProvider);

            var testContextProvider =
                contextProvider.Should().BeOfType<TestContextProvider>()
                .Subject;
            testContextProvider.Setting.Should().Be(setting);
            testContextProvider.Dependency.Should().BeSameAs(dependency);
        }

        [Fact(DisplayName = "AddContextProvider method throws when builder parameter is null")]
        public void AddContextProviderMethodSadPath()
        {
            ILoggerBuilder builder = null;

            Action act = () => builder.AddContextProvider<TestContextProvider>();

            act.Should().ThrowExactly<ArgumentNullException>().WithMessage("*builder*");
        }

        #region AddConsoleLogProvider

        [Fact(DisplayName = "AddConsoleLogProvider method 1 adds console log provider with specified template")]
        public void AddConsoleLogProviderMethod1HappyPath()
        {
            var builder = new TestLoggerBuilder();

            var template = "foobar";

            builder.AddConsoleLogProvider(template, LogLevel.Info);

            var registration =
                builder.LogProviderRegistrations.Should().ContainSingle()
                .Subject;

            var logProvider = registration.Invoke(_emptyServiceProvider);

            var consoleLogProvider =
                logProvider.Should().BeOfType<ConsoleLogProvider>()
                .Subject;

            consoleLogProvider.Level.Should().Be(LogLevel.Info);
            consoleLogProvider.Formatter.Should().BeOfType<TemplateLogFormatter>()
                .Which.Template.Should().Be(template);
        }

        [Fact(DisplayName = "AddConsoleLogProvider method 1 throws when template parameter is null")]
        public void AddConsoleLogProviderMethod1SadPath()
        {
            var builder = new Mock<ILoggerBuilder>().Object;

            Action act = () => builder.AddConsoleLogProvider((string)null, LogLevel.Info);

            act.Should().ThrowExactly<ArgumentNullException>().WithMessage("*template*");
        }

        [Fact(DisplayName = "Constructor sets properties")]
        public void ConstructorHappyPath1()
        {
            var services = new ServiceCollection();
            var name = "foo";
            Action<ILoggerOptions> configureOptions = o => o.Level = LogLevel.Info;

            var builder = new LoggerBuilder(services, name, configureOptions);

            builder.Services.Should().BeSameAs(services);
            builder.LoggerName.Should().BeSameAs(name);
            builder.ConfigureOptions.Should().BeSameAs(configureOptions);
        }

        [Fact(DisplayName = "Constructor sets LoggerName to Logger.DefaultName if name parameter is null")]
        public void ConstructorHappyPath2()
        {
            var services = new ServiceCollection();
            string name = null;
            Action<ILoggerOptions> configureOptions = o => o.Level = LogLevel.Info;

            var builder = new LoggerBuilder(services, name, configureOptions);

            builder.Services.Should().BeSameAs(services);
            builder.LoggerName.Should().BeSameAs(Logger.DefaultName);
            builder.ConfigureOptions.Should().BeSameAs(configureOptions);
        }

        [Fact(DisplayName = "Constructor throws if services parameter is null")]
        public void ConstructorSadPath()
        {
            IServiceCollection services = null;
            var name = "foo";
            Action<ILoggerOptions> configureOptions = o => o.Level = LogLevel.Info;

            Action act = () => new LoggerBuilder(services, name, configureOptions);

            act.Should().ThrowExactly<ArgumentNullException>().WithMessage("*services*");
        }

        [Fact(DisplayName = "AddLogProvider method adds logProviderRegistration parameter to configured LoggerOptions")]
        public void AddLogProviderMethodHappyPath()
        {
            var services = new ServiceCollection();
            var builder = new LoggerBuilder(services, Logger.DefaultName, null);

            var logProvider = new Mock<ILogProvider>().Object;

            Func<IServiceProvider, ILogProvider> logProviderRegistration = sp => logProvider;

            builder.AddLogProvider(logProviderRegistration);

            var serviceProvider = services.BuildServiceProvider();

            var optionsMonitor = serviceProvider.GetRequiredService<IOptionsMonitor<LoggerOptions>>();
            var options = optionsMonitor.Get(Logger.DefaultName);

            options.LogProviderRegistrations.Should().ContainSingle()
                .Which.Should().BeSameAs(logProviderRegistration);
        }

        [Fact(DisplayName = "AddLogProvider method throws if logProviderRegistration parameter is null")]
        public void AddLogProviderMethodSadPath()
        {
            var builder = new LoggerBuilder(new ServiceCollection(), Logger.DefaultName, null);

            Func<IServiceProvider, ILogProvider> logProviderRegistration = null;

            Action act = () => builder.AddLogProvider(logProviderRegistration);

            act.Should().ThrowExactly<ArgumentNullException>().WithMessage("*logProviderRegistration*");
        }

        [Fact(DisplayName = "AddContextProvider method adds contextProviderRegistration parameter to configured LoggerOptions")]
        public void AddContextProviderMethodHappyPath()
        {
            var services = new ServiceCollection();
            var builder = new LoggerBuilder(services, Logger.DefaultName, null);

            var contextProvider = new Mock<IContextProvider>().Object;

            Func<IServiceProvider, IContextProvider> contextProviderRegistration = sp => contextProvider;

            builder.AddContextProvider(contextProviderRegistration);

            var serviceProvider = services.BuildServiceProvider();

            var optionsMonitor = serviceProvider.GetRequiredService<IOptionsMonitor<LoggerOptions>>();
            var options = optionsMonitor.Get(Logger.DefaultName);

            options.ContextProviderRegistrations.Should().ContainSingle()
                .Which.Should().BeSameAs(contextProviderRegistration);
        }


        /// <summary>
        /// Check to see if the current file needs to be archived. If it does, archive it
        /// and prune the archive files if needed. Then, regardless of whether the file needed
        /// archiving, call the base method.
        /// </summary>
        /// <param name="formattedLogEntry">The formatted log entry.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
        /// <returns> A task that represents the asynchronous write operation.</returns>
        protected sealed override Task SynchronizedWriteAsync(string formattedLogEntry, CancellationToken cancellationToken)
        {
            if (NeedsArchiving())
            {
                ArchiveCurrentFile();
                PruneArchives();
            }

            return base.SynchronizedWriteAsync(formattedLogEntry, cancellationToken);
        }

        private bool NeedsArchiving()
        {
            var fileInfo = new FileInfo(File);

            return
                fileInfo.Exists
                && (ExceedsMaxFileSize(fileInfo) || NeedsNewRolloverPeriod(fileInfo));
        }

        private bool ExceedsMaxFileSize(FileInfo fileInfo) => fileInfo.Length > MaxFileSizeBytes;

        private bool NeedsNewRolloverPeriod(FileInfo fileInfo)
        {
            if (RolloverPeriod == RolloverPeriod.Never)
                return false;

            var currentTime = _getCurrentTime();
            var fileCreationTime = _getFileCreationTime(fileInfo);

            // Both Daily and Hourly roll over on a date change.
            if (currentTime.Date != fileCreationTime.Date)
                return true;

            // Hourly rolls over when the date is the same, but the hour is different.
            return
                RolloverPeriod == RolloverPeriod.Hourly
                && currentTime.Hour != fileCreationTime.Hour;
        }

        private void ArchiveCurrentFile() =>
            System.IO.File.Move(File, GetArchiveFileName());

        private string GetArchiveFileName()
        {
            var archiveFiles = GetArchiveFiles(out var directory, out var fileName, out var fileExtension);

            var archiveNumber =
                archiveFiles
                    .Select(f => f.ArchiveNumber)
                    .DefaultIfEmpty()
                    .Max() + 1;

            return Path.Combine(directory, fileName + "." + archiveNumber + fileExtension);
        }

RockLib.Logging.TemplateLogFormatter : ILogFormatter

Constructors :

public TemplateLogFormatter(String template = )

Methods :

public String get_Template()
public static Void AddExtendedPropertyTokenHandler(String key = , String extendedProperty = )
public static Void AddSimpleTokenHandler(String key = , Func<LogEntry, String> getValue = )
public String Format(LogEntry logEntry = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods