// TODO: not sure if this is the way we want to configure the logger, however, this // honors the principle of being a code based configuration vs XML/file based. public NLogFactory(LogFileSettings settings) { string fileName = settings.NamePrefix; string archiveFileName = settings.NamePrefix + ".{###}"; if (!string.IsNullOrEmpty(settings.ArchiveName)) { archiveFileName = settings.ArchiveName; } FileTarget target = new FileTarget { Layout = "${longdate} [${threadid}] ${level} ${logger} - ${message}", FileName = CreatePathFromSettings(settings.DirectoryPath, fileName, settings.Ext), ArchiveFileName = CreatePathFromSettings(settings.DirectoryPath, archiveFileName, settings.Ext), ArchiveEvery = ConvertRollingPeriod(settings.RolloverFrequency), ArchiveNumbering = ArchiveNumberingMode.Rolling, MaxArchiveFiles = 100, DeleteOldFileOnStartup = false, }; LoggingConfiguration config = new LoggingConfiguration(); LogLevel level = ConvertLogLevel(settings.Level); config.LoggingRules.Add(new LoggingRule("*", level, target)); // if the event log level is specified, then we will log the the Application EventLog. // Default is to only log Fatal messages. if (settings.EventLogLevel != LoggingLevel.Off) { EventLogTarget eventLogTarget = new EventLogTarget { Layout = "${logger}: ${message}${newline}${exception:format=ToString}", Source = settings.EventLogSource, Log = "Application", }; LogLevel eventLogLevel = ConvertLogLevel(settings.EventLogLevel); config.LoggingRules.Add(new LoggingRule("*", eventLogLevel, eventLogTarget)); } LogManager.Configuration = config; LogManager.ReconfigExistingLoggers(); }
/// <summary> /// This is a utility method to convert the values found in the LogFileSection /// to <see cref="LogFileSettings"/> and to substitute the appearance of a '~' /// for a call to <see cref="HttpServerUtility.MapPath"/> if this is run inside /// of a web context, or use the <see cref="Environment.CurrentDirectory"/>. /// </summary> /// <remarks>This assumes that there is <logging /> section in the app.config </remarks> /// <returns>A <see cref="LogFileSettings"/> object.</returns> public static LogFileSettings GetAsSettings() { LogFileSection section = (LogFileSection)ConfigurationManager.GetSection("logging"); if (section == null) { return(null); } LogFileSettings settings = section.ToSettings(); if (settings.DirectoryPath.Contains("~")) { string appDirectory = HostingEnvironment.ApplicationPhysicalPath ?? Environment.CurrentDirectory; settings.DirectoryPath = settings.DirectoryPath.Replace("~", appDirectory); } EventLogHelper.WriteInformation(settings.EventLogSource, "Writing log file to " + settings.DirectoryPath); return(settings); }