ConsoleLoggerProvider

We found 10 examples in language CSharp for this search. You will see 32 fragments of code.

Other methods


    public void Dispose()
    {
      LoggerFactory.Dispose();
      consoleLoggerProvider.Dispose();
    }


    public void Dispose()
    {
      LoggerFactory.Dispose();
      consoleLoggerProvider.Dispose();
    }


        public static void SetConsoleLogger()
        {
            ConsoleLoggerProvider consoleLoggerProvider = new ConsoleLoggerProvider((s, level) => true, false);
            InternalLoggerFactory.DefaultFactory.AddProvider(consoleLoggerProvider);
        }


        private static void EnsureIsSetup(ConsoleLoggerProvider consoleLoggerProvider)
        {
            var isSetup = consoleLoggerProvider.ConsoleLogMessageSink is object;
            if (!isSetup)
            {
                ConsoleLoggerProvider.PerformFirstTimeSetup(consoleLoggerProvider);
            }
        }

        public ILogger CreateLogger(string categoryName)
        {
            ConsoleLoggerProvider.EnsureIsSetup(this);

            var output = new ConsoleLogger(
                categoryName,
                this.ConsoleLogMessageSink);

            return output;
        }


    public void Dispose()
    {
      LoggerFactory.Dispose();
      consoleLoggerProvider.Dispose();
    }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddSimpleConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddSimpleConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddSystemdConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddSystemdConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddJsonConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddJsonConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddConsoleFormatter_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddConsoleFormatter<CustomFormatter, CustomOptions>(null);
                    }));
        }

        [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        [MemberData(nameof(FormatterNames))]
        public void AddConsole_ConsoleLoggerOptionsFromConfigFile_IsReadFromLoggingConfiguration(string formatterName)
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] {
                new KeyValuePair<string, string>("Console:FormatterName", formatterName)
            }).Build();

            var loggerProvider = new ServiceCollection()
                .AddLogging(builder => builder
                    .AddConfiguration(configuration)
                    .AddConsole())
                .BuildServiceProvider()
                .GetRequiredService<ILoggerProvider>();

            var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider);
            var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category");
            Assert.Equal(formatterName, logger.Options.FormatterName);
        }


        /// <summary>Loads the NLog.config file from the <see cref="DataFolder"/>, if it exists.</summary>
        public void LoadNLogConfiguration(DataFolder dataFolder)
        {
            if (dataFolder == null)
                return;

            string configPath = Path.Combine(dataFolder.RootPath, NLogConfigFileName);
            if (File.Exists(configPath))
                this.ConfigureNLog(configPath);
        }

        public static void RegisterFeatureNamespace<T>(string key)
        {
            keyCategories[key] = typeof(T).Namespace + ".*";
        }

        public static void RegisterFeatureClass<T>(string key)
        {
            keyCategories[key] = typeof(T).Namespace + "." + typeof(T).Name;
        }

        /// <summary>
        /// Event handler to be called when logging <see cref="NLog.LogManager.Configuration"/> gets reloaded.
        /// </summary>
        /// <param name="sender">Not used.</param>
        /// <param name="e">Not used.</param>
        public static void NLogConfigurationReloaded(object sender, LoggingConfigurationReloadedEventArgs e)
        {
            AddFilters(logSettings, folder);
        }

        /// <summary>
        /// Extends the logging rules in the "NLog.config" with node log settings rules.
        /// </summary>
        /// <param name="settings">Node log settings to extend the rules from the configuration file, or null if no extension is required.</param>
        /// <param name="dataFolder">Data folder to determine path to log files.</param>
        private static void AddFilters(LogSettings settings = null, DataFolder dataFolder = null)
        {
            if (settings == null) return;

            logSettings = settings;
            folder = dataFolder;

            // If we use "debug*" targets, which are defined in "NLog.config", make sure they log into the correct log folder in data directory.
            List<Target> debugTargets = LogManager.Configuration.AllTargets.Where(t => (t.Name != null) && t.Name.StartsWith("debug")).ToList();
            foreach (Target debugTarget in debugTargets)
            {
                FileTarget debugFileTarget = debugTarget is AsyncTargetWrapper ? (FileTarget)((debugTarget as AsyncTargetWrapper).WrappedTarget) : (FileTarget)debugTarget;
                string currentFile = debugFileTarget.FileName.Render(new LogEventInfo { TimeStamp = DateTime.UtcNow });
                debugFileTarget.FileName = Path.Combine(folder.LogPath, Path.GetFileName(currentFile));
            }

            // Remove rule that forbids logging before the logging is initialized.
            LoggingRule nullPreInitRule = null;
            foreach (LoggingRule rule in LogManager.Configuration.LoggingRules)
            {
                if (rule.Final && rule.NameMatches("*") && (rule.Targets.Count > 0) && (rule.Targets[0].Name == "null"))
                {
                    nullPreInitRule = rule;
                    break;
                }
            }

            LogManager.Configuration.LoggingRules.Remove(nullPreInitRule);

            // Configure main file target, configured using command line or node configuration file settings.
            var mainTarget = new FileTarget
            {
                Name = "main",
                FileName = Path.Combine(folder.LogPath, "node.txt"),
                ArchiveFileName = Path.Combine(folder.LogPath, "node-${date:universalTime=true:format=yyyy-MM-dd}.txt"),
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                ArchiveEvery = FileArchivePeriod.Day,
                MaxArchiveFiles = 7,
                Layout = "[${longdate:universalTime=true} ${threadid}${mdlc:item=id}] ${level:uppercase=true}: ${callsite} ${message}",
                Encoding = Encoding.UTF8
            };

            LogManager.Configuration.AddTarget(mainTarget);

            // Default logging level is Info for all components.
            var defaultRule = new LoggingRule($"{nameof(Stratis)}.{nameof(Bitcoin)}.*", settings.LogLevel, mainTarget);

            if (settings.DebugArgs.Any() && settings.DebugArgs[0] != "1")
            {
                var usedCategories = new HashSet<string>(StringComparer.Ordinal);

                // Increase selected categories to Debug.
                foreach (string key in settings.DebugArgs)
                {
                    if (!keyCategories.TryGetValue(key.Trim(), out string category))
                    {
                        // Allow direct specification - e.g. "-debug=Stratis.Bitcoin.Miner".
                        category = key.Trim();
                    }

                    if (!usedCategories.Contains(category))
                    {
                        usedCategories.Add(category);
                        var rule = new LoggingRule(category, settings.LogLevel, mainTarget);
                        LogManager.Configuration.LoggingRules.Add(rule);
                    }
                }
            }

            LogManager.Configuration.LoggingRules.Add(defaultRule);

            // Apply new rules.
            LogManager.ReconfigExistingLoggers();
        }

        /// <summary>
        /// Extends the logging rules in the "NLog.config" with node log settings rules.
        /// </summary>
        /// <param name="loggerFactory">Not used.</param>
        /// <param name="settings">Node log settings to extend the rules from the configuration file, or null if no extension is required.</param>
        /// <param name="dataFolder">Data folder to determine path to log files.</param>
        public static void AddFilters(this ILoggerFactory loggerFactory, LogSettings settings, DataFolder dataFolder)
        {
            AddFilters(settings, dataFolder);
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddSimpleConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddSimpleConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddSystemdConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddSystemdConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddJsonConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddJsonConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddConsoleFormatter_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddConsoleFormatter<CustomFormatter, CustomOptions>(null);
                    }));
        }

        [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        [MemberData(nameof(FormatterNames))]
        public void AddConsole_ConsoleLoggerOptionsFromConfigFile_IsReadFromLoggingConfiguration(string formatterName)
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] {
                new KeyValuePair<string, string>("Console:FormatterName", formatterName)
            }).Build();

            var loggerProvider = new ServiceCollection()
                .AddLogging(builder => builder
                    .AddConfiguration(configuration)
                    .AddConsole())
                .BuildServiceProvider()
                .GetRequiredService<ILoggerProvider>();

            var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider);
            var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category");
            Assert.Equal(formatterName, logger.Options.FormatterName);
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddSimpleConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddSimpleConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddSystemdConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddSystemdConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddJsonConsole_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddJsonConsole(null);
                    }));
        }

        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        public void AddConsoleFormatter_NullConfigure_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => 
                new ServiceCollection()
                    .AddLogging(builder => 
                    {
                        builder.AddConsoleFormatter<CustomFormatter, CustomOptions>(null);
                    }));
        }

        [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
        [MemberData(nameof(FormatterNames))]
        public void AddConsole_ConsoleLoggerOptionsFromConfigFile_IsReadFromLoggingConfiguration(string formatterName)
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] {
                new KeyValuePair<string, string>("Console:FormatterName", formatterName)
            }).Build();

            var loggerProvider = new ServiceCollection()
                .AddLogging(builder => builder
                    .AddConfiguration(configuration)
                    .AddConsole())
                .BuildServiceProvider()
                .GetRequiredService<ILoggerProvider>();

            var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider);
            var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category");
            Assert.Equal(formatterName, logger.Options.FormatterName);
        }

        [Fact]
        public void Can_AddProvider_Create_Logger()
        {
            var factory = new LoggerFactory();

            var provicer1 = new ConsoleLoggerProvider(LogLevel.Error);
            var provicer2 = new ConsoleLoggerProvider(LogLevel.Debug);

            factory.AddProvider(new[] { provicer1, provicer2 });

            var logger = factory.CreateLogger(this.GetType().Name);

            Assert.True(logger.IsEnabled(LogLevel.Debug));
        }

        [Fact]
        public void Can_Create_Logger_And_Append_Provider_()
        {
            var factory = new LoggerFactory();

            var provicer1 = new ConsoleLoggerProvider(LogLevel.Debug);

            factory.AddProvider(provicer1);

            var logger = factory.CreateLogger<LoggerTest>();

            Assert.True(logger.IsEnabled(LogLevel.Debug));

            var provicer2 = new ConsoleLoggerProvider(LogLevel.Warn);

            //append provider
            factory.AddProvider(provicer2);

            Assert.True(logger.IsEnabled(LogLevel.Warn));
        }

Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider : ILoggerProvider, IDisposable, ISupportExternalScope

Constructors :

public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options = )
public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options = , IEnumerable<ConsoleFormatter> formatters = )

Methods :

public ILogger CreateLogger(String name = )
public Void Dispose()
public Void SetScopeProvider(IExternalScopeProvider scopeProvider = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods