Exemplo n.º 1
0
        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);
        }