IBusControl ConfigureBus(IConfigurationRoot configuration) { var logFactory = new NLog.LogFactory(); logFactory.LoadConfiguration("nlog.config"); RabbitMqConfig configFromfile = configuration.GetSection("RabbitMq").Get <RabbitMqConfig>(); return(Bus.Factory.CreateUsingRabbitMq(cfg => { cfg.Host(configFromfile.HostUrl, (hostCfg) => { hostCfg.Username(configFromfile.Username); hostCfg.Password(configFromfile.Password); }); cfg.ReceiveEndpoint("user_created", e => { e.Consumer <UserCreatedConsumer>(() => { return new UserCreatedConsumer(new Common.LoggerHelper(logFactory.GetLogger("UserCreatedConsumer"))); }); }); })); }
public NLogTests(NLogConfiguration configuration = null) { factory = LoggerBuilders.BuildNLogFactory(configuration ?? new NLogConfiguration { KeepFileOpen = true }); logger = factory.GetLogger(nameof(IAuditLogger)); }
public void LogglyTargetTagsTest() { NLog.LogFactory logFactory = new NLog.LogFactory(); NLog.Config.LoggingConfiguration logConfig = CreateConfigurationFromString( @"<nlog throwExceptions='true'> <extensions> <add assembly='NLog.Targets.Loggly' /> </extensions> <targets> <target name='Loggly' type='Loggly' layout='${message}'> <tag name='hello' /> <tag name='${logger}' /> </target> </targets> <rules> <logger name='*' minlevel='Info' writeTo='Loggly' /> </rules> </nlog>", logFactory); var logglyTarget = logConfig.FindTargetByName("Loggly") as NLog.Targets.LogglyTarget; var logglyClientMock = new LogglyClientMock(); logglyTarget.ClientFactory = () => logglyClientMock; logFactory.Configuration = logConfig; NLog.Logger logger = logFactory.GetLogger(MethodInfo.GetCurrentMethod().Name); logger.Info("Hello World"); Assert.AreEqual(1, logglyClientMock.LogglyEvents.Count); Assert.AreEqual(2, logglyClientMock.LogglyEvents[0].Options.Tags.Count); Assert.AreEqual("hello", logglyClientMock.LogglyEvents[0].Options.Tags[0].Value); Assert.AreEqual(MethodInfo.GetCurrentMethod().Name, logglyClientMock.LogglyEvents[0].Options.Tags[1].Value); }
public void LogglyTargetContextPropertyTest() { NLog.LogFactory logFactory = new NLog.LogFactory(); NLog.Config.LoggingConfiguration logConfig = CreateConfigurationFromString( @"<nlog throwExceptions='true'> <extensions> <add assembly='NLog.Targets.Loggly' /> </extensions> <targets> <target name='Loggly' type='Loggly' layout='${message}' taskDelayMilliseconds='10'> <contextproperty name='hello' layout='${logger}' /> </target> </targets> <rules> <logger name='*' minlevel='Info' writeTo='Loggly' /> </rules> </nlog>", logFactory); var logglyTarget = logConfig.FindTargetByName("Loggly") as NLog.Targets.LogglyTarget; var logglyClientMock = new LogglyClientMock(); logglyTarget.ClientFactory = () => logglyClientMock; logFactory.Configuration = logConfig; NLog.Logger logger = logFactory.GetLogger(MethodInfo.GetCurrentMethod().Name); logger.Info("Hello World"); logglyClientMock.LogWritten.WaitOne(1000); Assert.AreEqual(1, logglyClientMock.LogglyEvents.Count); Assert.Contains("hello", logglyClientMock.LogglyEvents[0].Data.KeyList); Assert.AreEqual(MethodInfo.GetCurrentMethod().Name, logglyClientMock.LogglyEvents[0].Data["hello"]); }
public static ILogger GetLogger(string name) { var factory = new NLog.LogFactory(); var logger = factory.GetLogger(name); return(new Logger(logger)); }
public void LogglyTargetMdlcTest() { NLog.LogFactory logFactory = new NLog.LogFactory(); NLog.Config.LoggingConfiguration logConfig = CreateConfigurationFromString( @"<nlog throwExceptions='true'> <extensions> <add assembly='NLog.Targets.Loggly' /> </extensions> <targets> <target name='Loggly' type='Loggly' layout='${message}' includeMdlc='true'> </target> </targets> <rules> <logger name='*' minlevel='Info' writeTo='Loggly' /> </rules> </nlog>", logFactory); var logglyTarget = logConfig.FindTargetByName("Loggly") as NLog.Targets.LogglyTarget; var logglyClientMock = new LogglyClientMock(); logglyTarget.ClientFactory = () => logglyClientMock; logFactory.Configuration = logConfig; NLog.Logger logger = logFactory.GetLogger(MethodInfo.GetCurrentMethod().Name); using (NLog.MappedDiagnosticsLogicalContext.SetScoped("hello", logger.Name)) { logger.Info("Hello World"); Assert.AreEqual(1, logglyClientMock.LogglyEvents.Count); Assert.Contains("hello", logglyClientMock.LogglyEvents[0].Data.KeyList); Assert.AreEqual(MethodInfo.GetCurrentMethod().Name, logglyClientMock.LogglyEvents[0].Data["hello"]); } }
public void ContextPropertiesILoggerTest() { var logFactory = new NLog.LogFactory(); var logConfig = new NLog.Config.LoggingConfiguration(); var ilogger = new TestLogger(); var target = new MicrosoftILoggerTarget(ilogger) { Layout = "${message}" }; target.ContextProperties.Add(new Targets.TargetPropertyWithContext() { Name = "ThreadId", Layout = "${threadid}" }); logConfig.AddRuleForAllLevels(target); logFactory.Configuration = logConfig; var logger = logFactory.GetCurrentClassLogger(); logger.Info("Hello {Planet}", "Earth"); Assert.Equal("Hello \"Earth\"", ilogger.LastLogMessage); Assert.Equal(3, ilogger.LastLogProperties.Count); Assert.Equal("Planet", ilogger.LastLogProperties[0].Key); Assert.Equal("Earth", ilogger.LastLogProperties[0].Value); Assert.Equal("ThreadId", ilogger.LastLogProperties[1].Key); Assert.Equal(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), ilogger.LastLogProperties[1].Value); Assert.Equal("Hello {Planet}", ilogger.LastLogProperties[2].Value); }
public void Aggregate_And_AppendProvider() { //def console LoggerFactory.Factory.AddConsole(LogLevel.Trace); //print 1 line _logger.Info("------- console -------"); var config = new NLog.Config.LoggingConfiguration(); var consoleTarget = new NLog.Targets.ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var rule1 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, consoleTarget); config.LoggingRules.Add(rule1); var factory = new NLog.LogFactory(config); //append NLog LoggerFactory.Factory.AddNLog(factory); //print 2 line _logger.Info("------- console & nlog -------"); }
public void W3CLoggerLayoutWithContextTest() { var httpContextMock = SetupHttpAccessorWithHttpContext("nlog-project.org:80", "http", "/Test.asp", "?t=1"); var logFactory = new NLog.LogFactory().Setup().SetupExtensions(ext => ext.RegisterAssembly(typeof(NLog.Web.Layouts.W3CExtendedLogLayout).Assembly)).LoadConfiguration(builder => { var layout = new NLog.Web.Layouts.W3CExtendedLogLayout(); var headerTarget = new NLog.Targets.MemoryTarget() { Name = "Header", Layout = layout.Header }; var bodyTarget = new NLog.Targets.MemoryTarget() { Name = "Body", Layout = layout }; builder.Configuration.AddRuleForAllLevels(headerTarget); builder.Configuration.AddRuleForAllLevels(bodyTarget); }).LogFactory; var logger = logFactory.GetCurrentClassLogger(); var logEvent = new LogEventInfo(LogLevel.Info, null, "RequestLogging"); logger.Log(logEvent); string expectedFieldHeaders = "c-ip cs-username s-computername cs-method cs-uri-stem cs-uri-query sc-status sc-bytes cs-bytes time-taken cs-host cs(User-Agent)"; string expectedFieldValues = $"- - {Environment.MachineName} - /Test.asp ?t=1 200 7 42 - nlog-project.org -"; string expectedHeader = $@"#Software: Microsoft Internet Information Server{System.Environment.NewLine}#Version: 1.0{System.Environment.NewLine}#Start-Date: {logEvent.TimeStamp.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)}{System.Environment.NewLine}#Fields: date time {expectedFieldHeaders}"; string expectedBody = $@"{logEvent.TimeStamp.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)} {expectedFieldValues}"; var header = logFactory.Configuration.FindTargetByName <NLog.Targets.MemoryTarget>("Header")?.Logs?.FirstOrDefault(); var body = logFactory.Configuration.FindTargetByName <NLog.Targets.MemoryTarget>("Body")?.Logs?.FirstOrDefault(); Assert.Equal(expectedHeader, header); Assert.Equal(expectedBody, body); }
private ILogger GetLogger() { var configFile = new NLog.Config.XmlLoggingConfiguration("D:\\home\\site\\wwwroot\\Nlog.config"); var factory = new NLog.LogFactory(configFile); NLogLoggerProvider provider = new NLogLoggerProvider(new NLogProviderOptions(), factory); return(provider.CreateLogger(ATFLoggerName)); }
static void Main(string[] args) { var config = new NLog.Config.LoggingConfiguration(); using (var fluentdTarget = new NLog.Targets.Fluentd()) { fluentdTarget.Layout = new NLog.Layouts.SimpleLayout("${longdate}|${level}|${callsite}|${logger}|${message}"); config.AddTarget("fluentd", fluentdTarget); config.LoggingRules.Add(new NLog.Config.LoggingRule("demo", NLog.LogLevel.Debug, fluentdTarget)); var loggerFactory = new NLog.LogFactory(config); var logger = loggerFactory.GetLogger("demo"); logger.Info("Hello World!"); } }
public void IsLogExhaustiveTest() { var levels = System.Enum.GetValues(typeof(NatvisLoggingLevel)) .Cast <NatvisLoggingLevel>(); var logFactory = new NLog.LogFactory(); var logger = new NatvisDiagnosticLogger(logFactory.CreateNullLogger(), levels.Max()); // Make sure that all logging level switch is exhaustive. // <c>logger.Log(...)</c> will throw an exception if the passed in level is not handled. foreach (var level in levels) { logger.Log(level, "test message"); } }
/// <summary> /// The entry point of the SynchroFeed.Listener application. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { var logFactory = new NLog.LogFactory(); var logger = logFactory.GetLogger("SynchroFeed.Listener.Program"); logger.Log(NLog.LogLevel.Info, "SynchroFeed.Listener Starting"); logger.Log(NLog.LogLevel.Debug, $"args length: {args.Length}"); foreach (var arg in args) { logger.Log(NLog.LogLevel.Debug, $"arg: {arg}"); } var commandLineApp = new ListenerCommandLine(); Environment.ExitCode = Execute(commandLineApp, logger); }
private void InitNLog(string logFile) { var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logFile, Layout = "${message}" }; config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logfile); var logFactory = new NLog.LogFactory(config); _nLogLogger = logFactory.GetCurrentClassLogger(); }
public void FilterILoggerMessageTest() { var logFactory = new NLog.LogFactory(); var logConfig = new NLog.Config.LoggingConfiguration(); var ilogger = new TestLogger(); logConfig.AddRuleForAllLevels(new MicrosoftILoggerTarget(ilogger) { Layout = "${message}" }); logFactory.Configuration = logConfig; var logger = logFactory.GetCurrentClassLogger(); logger.Debug("Hello World"); Assert.Null(ilogger.LastLogMessage); }
public void RegisterNLogWebTest() { // Act var logFactory = new NLog.LogFactory().Setup().RegisterNLogWeb().LoadConfigurationFromXml( @"<nlog throwConfigExceptions='true'> <targets> <target type='AspNetBufferingWrapper' name='hello'> <target type='Memory' name='hello_wrapped' /> </target> </targets> <rules> <logger name='*' writeTo='hello' /> </rules> </nlog>").LogFactory; // Assert Assert.NotNull(logFactory?.Configuration?.FindTargetByName <AspNetBufferingTargetWrapper>("hello")); }
public void SimpleILoggerMessageTest() { var logFactory = new NLog.LogFactory(); var logConfig = new NLog.Config.LoggingConfiguration(); var ilogger = new TestLogger(); logConfig.AddRuleForAllLevels(new MicrosoftILoggerTarget(ilogger) { Layout = "${message}" }); logFactory.Configuration = logConfig; var logger = logFactory.GetCurrentClassLogger(); logger.Info("Hello World"); Assert.Equal("Hello World", ilogger.LastLogMessage); Assert.Single(ilogger.LastLogProperties); Assert.Equal("Hello World", ilogger.LastLogProperties[0].Value); }
/// <summary> /// Get type specific logger, or fallback logger. /// </summary> /// <param name="line"></param> /// <returns>logger or null if has been disposed</returns> NLog.ILogger Logger(ILine line) { NLog.LogFactory _logFactory = logFactory; if (_logFactory == null) { return(null); } ILine type = line.FindTypeKey(); if (type is ILineType lineType && lineType.Type != null) { return(_logFactory.GetLogger(lineType.Type.FullName, lineType.Type)); } if (type is ILineParameter lineParameter && lineParameter.ParameterValue != null) { return(_logFactory.GetLogger(lineParameter.ParameterValue)); } return(fallbackLogger); }
protected void Application_Start() { var factory = new NLog.LogFactory(); var logger = factory.GetLogger("Default"); logger.Debug("Iniciando app..."); HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize(); AreaRegistration.RegisterAllAreas(); // Use LocalDB for Entity Framework by default Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True"); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); logger.Debug("App Iniciada"); }
public void StructuredILoggerMessageTest() { var logFactory = new NLog.LogFactory(); var logConfig = new NLog.Config.LoggingConfiguration(); var ilogger = new TestLogger(); logConfig.AddRuleForAllLevels(new MicrosoftILoggerTarget(ilogger) { Layout = "${message}" }); logFactory.Configuration = logConfig; var logger = logFactory.GetCurrentClassLogger(); logger.Info("Hello {Planet}", "Earth"); Assert.Equal("Hello \"Earth\"", ilogger.LastLogMessage); Assert.Equal(2, ilogger.LastLogProperties.Count); Assert.Equal("Planet", ilogger.LastLogProperties[0].Key); Assert.Equal("Earth", ilogger.LastLogProperties[0].Value); Assert.Equal("Hello {Planet}", ilogger.LastLogProperties[1].Value); }
public void Aggregate_And_AppendProvider() { //def console LoggerManager.Factory.AddConsole(LogLevel.Trace); _logger.Info("------- console -------"); var config = new NLog.Config.LoggingConfiguration(); var consoleTarget = new NLog.Targets.ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var rule1 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, consoleTarget); config.LoggingRules.Add(rule1); var factory = new NLog.LogFactory(config); //append NLog LoggerManager.Factory.AddNLog(factory); _logger.Info("------- console & nlog -------"); }
static Program() { string mysql_conn = ""; logFactory = NLog.LogManager.LoadConfiguration("nlog.config"); logger = logFactory.GetLogger("CumulateHourlyApp"); #if DEBUG Console.WriteLine("DEBUG MODE"); string influx_hostname = "http://192.168.0.40:8086"; string influx_username = "******"; string influx_password = "******"; mysql_conn = PeiuPlatform.DataAccessor.DataAccessorBase.CreateConnectionString("192.168.0.40", "3306", "power21", "123qwe"); dataAccessor = new MysqlDataAccessor(mysql_conn); #else string influx_hostname = Environment.GetEnvironmentVariable(ENV_INFLUXDB_HOST); string influx_username = Environment.GetEnvironmentVariable(ENV_INFLUXDB_USERNAME); string influx_password = Environment.GetEnvironmentVariable(ENV_INFLUXDB_PASSWORD); dataAccessor = MysqlDataAccessor.CreateDataAccessFromEnvironment(); #endif influxDBClient = new InfluxDBClient(influx_hostname, influx_username, influx_password); }
private static NLogLoggerProvider CreateNLogLoggerProvider(IServiceProvider serviceProvider, IConfiguration configuration, NLogAspNetCoreOptions options, NLog.LogFactory logFactory) { NLogLoggerProvider provider = new NLogLoggerProvider(options ?? NLogAspNetCoreOptions.Default, logFactory ?? LogManager.LogFactory); configuration = SetupConfiguration(serviceProvider, configuration); if (serviceProvider != null && provider.Options.RegisterServiceProvider) { provider.LogFactory.ServiceRepository.RegisterService(typeof(IServiceProvider), serviceProvider); } if (configuration != null) { provider.Configure(configuration.GetSection("Logging:NLog")); TryLoadConfigurationFromSection(provider, configuration); } if (provider.Options.ShutdownOnDispose) { provider.LogFactory.AutoShutdown = false; } return(provider); }
private static NLogLoggerProvider CreateNLogLoggerProvider(IServiceProvider serviceProvider, IConfiguration configuration, NLogAspNetCoreOptions options, NLog.LogFactory logFactory) { configuration = SetupConfiguration(serviceProvider, configuration); NLogLoggerProvider provider = new NLogLoggerProvider(options ?? NLogAspNetCoreOptions.Default, logFactory ?? LogManager.LogFactory); if (configuration != null && options == null) { provider.Configure(configuration.GetSection("Logging:NLog")); } return(provider); }
/// <summary> /// Append <paramref name="nlogfactory"/> logger to <paramref name="line"/>. /// /// Writes log messages to NLog in a way that type specific log events are directed to the respective type. /// /// </summary> /// <param name="line"></param> /// <param name="nlogfactory">NLog Logger</param> /// <param name="fallbackCategory">(optional) logger name to use when Type cannot be derived</param> /// <returns>disposable subscription handle, or null if <paramref name="line"/> cannot be observed</returns> public static ILineLogger NLog(this ILine line, NLog.LogFactory nlogfactory, string fallbackCategory = "Lexical.Localization") => line.Logger(new NLogFactoryLocalizationLogger(nlogfactory, fallbackCategory));
private static void Main() { var client = new BattleNetClient( "http://dojorena.io/codenjoy-contest/board/player/ix61eg04ddy0dtfh3ckq?code=382142621680346506&gameName=battlecity"); var analitics = new RegionAnalysis(client); var fightProgram = new FightProgram(client); var moveProgram = new MoveProgram(client); var wayOutProgram = new WayOutProgram(client); var defenseProgram = new DefenseProgram(client); var commandsUtility = new CommandsProcessor(client); var logger = new NLog.LogFactory().GetCurrentClassLogger(); client.Run(() => { try { Stopwatch timer = Stopwatch.StartNew(); if (!client.IsPlayerAlive()) { client.SendActions(client.Blank()); logger.Debug("Our tank had been destroyed"); return; } logger.Debug($"Current coordinates [{client.PlayerX}, {client.PlayerY}]"); //var freeRegion = analitics.GetFreeRegion(); var freeRegion = new Region(new Region(client.PlayerY, client.PlayerY, client.PlayerX, client.PlayerX), 6); //logger.Debug($"Region analitics finished {freeRegion.ToString()}"); //var enemiesInArea = client.GetEnemiesPoints(freeRegion); var enemiesInArea = client.GetEnemiesPoints(freeRegion); logger.Debug($"Enemy search region {freeRegion.ToString()}"); var enemiesCount = enemiesInArea.Count; logger.Debug($"Enemies {enemiesCount} found at region"); if (enemiesCount > 0) { logger.Debug($"Closest enemy at {analitics.GetClosestEnemy(freeRegion)} found at region"); } var preAct = false; var movement = Movement.Stop; var postAct = false; if (defenseProgram.CanBeUsed()) { logger.Debug("Defense mode used"); movement = moveProgram.GetSafeMovementDirection(defenseProgram.DangerDirections); } else if (fightProgram.CanBeUsed(6)) { logger.Debug("Fight mode used"); //preAct = fightProgram.TryPreAct(enemiesInArea); movement = moveProgram.GetMovementToClosestEnemy(); postAct = fightProgram.TryPostAct(movement.ToDirection(client), enemiesInArea); } else if (wayOutProgram.CanBeUsed(6)) { logger.Debug("WayOut mode used"); //preAct = wayOutProgram.TryPreAct(freeRegion); movement = moveProgram.GetMovementToClosestConstruction(); postAct = true; //wayOutProgram.TryPostAct(movement.ToDirection(client), freeRegion); } else { logger.Debug("default mode used"); //Move(client); movement = moveProgram.GetLongTermRandomDirection(); } var command = commandsUtility.CreateCommand(preAct, movement, postAct); logger.Debug($"Command sending [{command}]"); client.SendActions(command); timer.Stop(); logger.Debug($"Turn finished in {timer.ElapsedMilliseconds} ms"); } catch (Exception e) { logger.Fatal(e, "Programm ended\n"); throw; } }); Console.Read(); }
public static XmlLoggingConfiguration CreateConfigurationFromString(string configXml, NLog.LogFactory logFactory) { XmlDocument doc = new XmlDocument(); doc.LoadXml(configXml); using (var stringReader = new StringReader(doc.DocumentElement.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); return(new XmlLoggingConfiguration(reader, null, false, logFactory)); } }
protected virtual void ConfigureLogging(IApplicationBuilder app) { var hostingEnvironment = app.ApplicationServices.GetRequiredService<IHostingEnvironment>(); var applicationEnvironment = app.ApplicationServices.GetRequiredService<IApplicationEnvironment>(); var loggerFactory = app.ApplicationServices.GetRequiredService<LoggerFactory>(); var nlogConfigFileGenerated = false; var nlogConfigFilename = "NLog.config"; var nlogConfigSearchPaths = new string[] { ".", applicationEnvironment.ApplicationBasePath }; var nlogConfigFilePath = PathUtils.FindPath(nlogConfigSearchPaths, nlogConfigFilename); // If no NLog.config file is found, generate one to use. // The stub is created so that admins can edit and configure // logging even in cases where a file was not provided. if (nlogConfigFilePath == null) { nlogConfigFileGenerated = true; nlogConfigFilePath = Path.Combine(applicationEnvironment.ApplicationBasePath, "NLog.config"); File.WriteAllText(nlogConfigFilePath, @"<?xml version=""1.0"" encoding=""utf-8"" ?> <nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" autoReload=""true"" > <targets> <target name=""Console"" xsi:type=""ColoredConsole"" layout=""[${pad:padding=7:inner=${level:uppercase=true}}] ${logger}: ${message}""/> </targets> <rules> <logger name=""*"" minlevel=""Info"" writeTo=""console"" /> </rules> </nlog> "); } var nlogFactory = new NLog.LogFactory(new XmlLoggingConfiguration(nlogConfigFilePath) { AutoReload = true }); loggerFactory.AddNLog(nlogFactory); ApplicationLog = loggerFactory.CreateLogger("Application"); ApplicationLog.LogInformation("Log file opened at {0}.", DateTime.Now); if (nlogConfigFileGenerated) { ApplicationLog.LogWarning("NLog configuration file could not be found. A new one has been generated."); } ApplicationLog.LogInformation("Logging configuration file: {0}", nlogConfigFilePath); AccessLog = loggerFactory.CreateLogger("Access"); AccessLog.LogInformation("Log file opened at {0}.", DateTime.Now); HtmlAccessLog = loggerFactory.CreateLogger("HtmlAccess"); HtmlAccessLog.LogInformation("Log file opened at {0}.", DateTime.Now); }
/// <summary> /// Logging is closed. /// </summary> public void OnCompleted() { logFactory = null; fallbackLogger = null; }
public NLogAdapter() { _logger = new NLog.LogFactory().GetLogger("ClinicArrivals"); }
protected virtual void ConfigureLogging(IApplicationBuilder app) { var hostingEnvironment = app.ApplicationServices.GetRequiredService <IHostingEnvironment>(); var applicationEnvironment = app.ApplicationServices.GetRequiredService <IApplicationEnvironment>(); var loggerFactory = app.ApplicationServices.GetRequiredService <LoggerFactory>(); var nlogConfigFileGenerated = false; var nlogConfigFilename = "NLog.config"; var nlogConfigSearchPaths = new string[] { ".", applicationEnvironment.ApplicationBasePath }; var nlogConfigFilePath = PathUtils.FindPath(nlogConfigSearchPaths, nlogConfigFilename); // If no NLog.config file is found, generate one to use. // The stub is created so that admins can edit and configure // logging even in cases where a file was not provided. if (nlogConfigFilePath == null) { nlogConfigFileGenerated = true; nlogConfigFilePath = Path.Combine(applicationEnvironment.ApplicationBasePath, "NLog.config"); File.WriteAllText(nlogConfigFilePath, @"<?xml version=""1.0"" encoding=""utf-8"" ?> <nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" autoReload=""true"" > <targets> <target name=""Console"" xsi:type=""ColoredConsole"" layout=""[${pad:padding=7:inner=${level:uppercase=true}}] ${logger}: ${message}""/> </targets> <rules> <logger name=""*"" minlevel=""Info"" writeTo=""console"" /> </rules> </nlog> "); } var nlogFactory = new NLog.LogFactory(new XmlLoggingConfiguration(nlogConfigFilePath) { AutoReload = true }); loggerFactory.AddNLog(nlogFactory); ApplicationLog = loggerFactory.CreateLogger("Application"); ApplicationLog.LogInformation("Log file opened at {0}.", DateTime.Now); if (nlogConfigFileGenerated) { ApplicationLog.LogWarning("NLog configuration file could not be found. A new one has been generated."); } ApplicationLog.LogInformation("Logging configuration file: {0}", nlogConfigFilePath); AccessLog = loggerFactory.CreateLogger("Access"); AccessLog.LogInformation("Log file opened at {0}.", DateTime.Now); HtmlAccessLog = loggerFactory.CreateLogger("HtmlAccess"); HtmlAccessLog.LogInformation("Log file opened at {0}.", DateTime.Now); }
/// <summary> /// Create logger /// </summary> /// <param name="logFactory"></param> /// <param name="fallbackCategory"></param> public NLogFactoryLocalizationLogger(NLog.LogFactory logFactory, string fallbackCategory = "Lexical.Localization") { this.logFactory = logFactory ?? throw new ArgumentNullException(nameof(logFactory)); this.fallbackLogger = logFactory.GetLogger(fallbackCategory); }