public void SimpleFileTest1() { var tempFile = Path.GetTempFileName(); try { var ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", OpenFileCacheTimeout = 0 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { if (File.Exists(tempFile)) { File.Delete(tempFile); } } }
public void FileTarget_InvalidFileNameCorrection() { var tempFile = Path.GetTempFileName(); var invalidTempFile = tempFile + Path.GetInvalidFileNameChars()[0]; var expectedCorrectedTempFile = tempFile + "_"; try { var ft = new FileTarget { FileName = SimpleLayout.Escape(invalidTempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", OpenFileCacheTimeout = 0 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Fatal); logger.Fatal("aaa"); LogManager.Configuration = null; AssertFileContents(expectedCorrectedTempFile, "Fatal aaa\n", Encoding.UTF8); } finally { if (File.Exists(invalidTempFile)) { File.Delete(invalidTempFile); } if (File.Exists(expectedCorrectedTempFile)) { File.Delete(expectedCorrectedTempFile); } } }
protected override void InitializeTarget() { base.InitializeTarget(); bool foundProvider = false; #if !NET_CF if (!string.IsNullOrEmpty(this.ConnectionStringName)) { // read connection string and provider factory from the configuration file var cs = this.ConnectionStringsSettings[this.ConnectionStringName]; if (cs == null) { throw new NLogConfigurationException("Connection string '" + this.ConnectionStringName + "' is not declared in <connectionStrings /> section."); } this.ConnectionString = SimpleLayout.Escape(cs.ConnectionString); this.ProviderFactory = DbProviderFactories.GetFactory(cs.ProviderName); foundProvider = true; } if (!foundProvider) { foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows) { if ((string)row["InvariantName"] == this.DBProvider) { this.ProviderFactory = DbProviderFactories.GetFactory(this.DBProvider); foundProvider = true; } } } #endif if (!foundProvider) { switch (this.DBProvider.ToUpper(CultureInfo.InvariantCulture)) { case "SQLSERVER": case "MSSQL": case "MICROSOFT": case "MSDE": this.ConnectionType = systemDataAssembly.GetType("System.Data.SqlClient.SqlConnection", true); break; case "OLEDB": this.ConnectionType = systemDataAssembly.GetType("System.Data.OleDb.OleDbConnection", true); break; case "ODBC": this.ConnectionType = systemDataAssembly.GetType("System.Data.Odbc.OdbcConnection", true); break; default: this.ConnectionType = Type.GetType(this.DBProvider, true); break; } } }
private static void AssertEscapeRoundTrips(string originalString) { string escapedString = SimpleLayout.Escape(originalString); SimpleLayout l = escapedString; string renderedString = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(originalString, renderedString); }
private static void SetupNLog() { LogManager.KeepVariablesOnReload = true; //Create configuration object var config = new LoggingConfiguration(); //Define log name if (config.Variables.ContainsKey("logName")) { config.Variables["logName"] = "DaemonMaster_Service"; } else { config.Variables.Add("logName", SimpleLayout.Escape("DaemonMaster_Service")); } //Create targets and adding rules var consoleTarget = new ColoredConsoleTarget("consoleTarget") { Layout = @"${date:format=HH\:mm\:ss} ${level:uppercase=true} ${message} ${newline} ${exception:format=ToString}", DetectConsoleAvailable = true }; config.AddTarget(consoleTarget); config.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget);// only infos and higher //#if DEBUG // var debugFileTarget = new FileTarget("debugFileTarget") // { // FileName = @"${basedir}\logs\Debug_${logDir}${var:logName}.${shortdate}.log", // Layout = @"${longdate}|${level:uppercase=true}|${exception:format=ToString,StackTrace}|${logger}|${message}", // ArchiveOldFileOnStartup = true, // ArchiveFileName = @"${basedir}\logs\archive\Debug_${archiveDir}${var:logName}.${shortdate}.{#####}.log", // ArchiveNumbering = ArchiveNumberingMode.Sequence, // MaxArchiveFiles = 10 // }; // config.AddTarget(debugFileTarget); // config.AddRuleForAllLevels(debugFileTarget); //#else // var fileTarget = new FileTarget("fileTarget") // { // FileName = @"${basedir}\logs\${logDir}${var:logName}.${shortdate}.log", // Layout = @"${longdate}|${level:uppercase=true}|${exception:format=ToString,StackTrace}|${logger}|${message}", // ArchiveOldFileOnStartup = true, // ArchiveFileName = @"${basedir}\logs\archive\${var:logName}.${shortdate}.{#####}.log", // ArchiveNumbering = ArchiveNumberingMode.Sequence, // MaxArchiveFiles = 10 // }; // config.AddTarget(fileTarget); // config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget); // only infos and higher //#endif //Activate the configuration LogManager.Configuration = config; LogManager.ReconfigExistingLoggers(); }
protected override void InitializeTarget() { base.InitializeTarget(); #pragma warning disable 618 if (UseTransactions.HasValue) #pragma warning restore 618 { InternalLogger.Warn("UseTransactions property is obsolete and will not be used - will be removed in NLog 6"); } bool foundProvider = false; #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) { // read connection string and provider factory from the configuration file var cs = ConnectionStringsSettings[ConnectionStringName]; if (cs == null) { throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section."); } ConnectionString = SimpleLayout.Escape(cs.ConnectionString); if (!string.IsNullOrEmpty(cs.ProviderName)) { ProviderFactory = DbProviderFactories.GetFactory(cs.ProviderName); foundProvider = true; } } if (!foundProvider) { foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows) { var invariantname = (string)row["InvariantName"]; if (invariantname == DBProvider) { ProviderFactory = DbProviderFactories.GetFactory(DBProvider); foundProvider = true; break; } } } #endif if (!foundProvider) { SetConnectionType(); } }
public void CsvHeaderTest() { // test for the following changes // https://github.com/NLog/NLog/commit/e1ed0d4857dddc95d5db09ee95e9a0c85afc7810 // codeplex ticket 6370 string tempFile = Path.GetTempFileName(); try { for (int i = 0; i < 2; i++) { var layout = new CsvLayout { Delimiter = CsvColumnDelimiterMode.Semicolon, WithHeader = true, Columns = { new CsvColumn("name", "${logger}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), } }; FileTarget ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = layout, OpenFileCacheTimeout = 0, ReplaceFileContentsOnEachWrite = false }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); LogManager.Configuration = null; } AssertFileContents(tempFile, "name;level;message\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\n", Encoding.UTF8); } finally { if (File.Exists(tempFile)) { File.Delete(tempFile); } } }
public void CsvHeaderTest() { var tempFile = Path.GetTempFileName(); try { for (var i = 0; i < 2; i++) { var layout = new CsvLayout { Delimiter = CsvColumnDelimiterMode.Semicolon, WithHeader = true, Columns = { new CsvColumn("name", "${logger}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), } }; var ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = layout, OpenFileCacheTimeout = 0, ReplaceFileContentsOnEachWrite = false }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); LogManager.Configuration = null; } AssertFileContents(tempFile, "name;level;message\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\n", Encoding.UTF8); } finally { if (File.Exists(tempFile)) { File.Delete(tempFile); } } }
protected override void InitializeTarget() { base.InitializeTarget(); #pragma warning disable 618 if (UseTransactions.HasValue) #pragma warning restore 618 { InternalLogger.Warn("UseTransactions is obsolete and will not be used - will be removed in NLog 6"); } bool foundProvider = false; if (!string.IsNullOrEmpty(this.ConnectionStringName)) { // read connection string and provider factory from the configuration file var cs = this.ConnectionStringsSettings[this.ConnectionStringName]; if (cs == null) { throw new NLogConfigurationException("Connection string '" + this.ConnectionStringName + "' is not declared in <connectionStrings /> section."); } this.ConnectionString = SimpleLayout.Escape(cs.ConnectionString); if (!string.IsNullOrEmpty(cs.ProviderName)) { this.ProviderFactory = DbProviderFactories.GetFactory(cs.ProviderName); foundProvider = true; } } if (!foundProvider) { foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows) { var invariantname = (string)row["InvariantName"]; if (invariantname == this.DBProvider) { this.ProviderFactory = DbProviderFactories.GetFactory(this.DBProvider); foundProvider = true; break; } } } if (!foundProvider) { switch (this.DBProvider.ToUpper(CultureInfo.InvariantCulture)) { case "SQLSERVER": case "MSSQL": case "MICROSOFT": case "MSDE": this.ConnectionType = systemDataAssembly.GetType("System.Data.SqlClient.SqlConnection", true); break; case "OLEDB": this.ConnectionType = systemDataAssembly.GetType("System.Data.OleDb.OleDbConnection", true); break; case "ODBC": this.ConnectionType = systemDataAssembly.GetType("System.Data.Odbc.OdbcConnection", true); break; default: this.ConnectionType = Type.GetType(this.DBProvider, true); break; } } }
public void DeleteFileOnStartTest() { var tempFile = Path.GetTempFileName(); try { var ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // configure again, without // DeleteOldFileOnStartup ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // configure again, this time with // DeleteOldFileOnStartup ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", DeleteOldFileOnStartup = true }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) { File.Delete(tempFile); } } }
public void ArchiveFileOnStartTest() { var tempFile = Path.GetTempFileName(); var tempArchiveFolder = Path.Combine(Path.GetTempPath(), "Archive"); try { // Configure first time with ArchiveOldFileOnStartup = false. var ft = new FileTarget { ArchiveOldFileOnStartup = false, FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // Configure second time with ArchiveOldFileOnStartup = false again. // Expected behavior: Extra content to be appended to the file. ft = new FileTarget { ArchiveOldFileOnStartup = false, FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // Configure third time with ArchiveOldFileOnStartup = true again. // Expected behavior: Extra content will be stored in a new file; the // old content should be moved into a new location. var archiveTempName = Path.Combine(tempArchiveFolder, "archive.txt"); ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", ArchiveOldFileOnStartup = true, ArchiveFileName = archiveTempName, ArchiveNumbering = ArchiveNumberingMode.Sequence, MaxArchiveFiles = 1 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("ddd"); logger.Info("eee"); logger.Warn("fff"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug ddd\nInfo eee\nWarn fff\n", Encoding.UTF8); Assert.True(File.Exists(archiveTempName)); AssertFileContents(archiveTempName, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) { File.Delete(tempFile); } if (Directory.Exists(tempArchiveFolder)) { Directory.Delete(tempArchiveFolder, true); } } }
public void ArchiveFileOnStartTest() { var tempFile = Path.GetTempFileName(); var tempArchiveFolder = Path.Combine(Path.GetTempPath(), "Archive"); try { var ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // configure again, without // ArchiveOldFileOnStartup ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // configure again, this time with // ArchiveldFileOnStartup var archiveTempName = Path.Combine(tempArchiveFolder, "archive.txt"); ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", ArchiveOldFileOnStartup = true, ArchiveNumbering = ArchiveNumberingMode.Sequence, ArchiveFileName = archiveTempName }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("ddd"); logger.Info("eee"); logger.Warn("fff"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug ddd\nInfo eee\nWarn fff\n", Encoding.UTF8); AssertFileContents(archiveTempName, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) { File.Delete(tempFile); } if (Directory.Exists(tempArchiveFolder)) { Directory.Delete(tempArchiveFolder, true); } } }
protected override void InitializeTarget() { base.InitializeTarget(); #pragma warning disable 618 if (UseTransactions.HasValue) #pragma warning restore 618 { InternalLogger.Warn("UseTransactions property is obsolete and will not be used - will be removed in NLog 6"); } bool foundProvider = false; string providerName = string.Empty; #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) { // read connection string and provider factory from the configuration file var cs = ConnectionStringsSettings[ConnectionStringName]; if (cs == null) { throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section."); } ConnectionString = SimpleLayout.Escape(cs.ConnectionString); if (!string.IsNullOrEmpty(cs.ProviderName)) { providerName = cs.ProviderName; } } #endif if (ConnectionString != null) { try { var connectionString = BuildConnectionString(LogEventInfo.CreateNullEvent()); var dbConnectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (dbConnectionStringBuilder.TryGetValue("provider connection string", out var connectionStringValue)) { // Special Entity Framework Connection String if (dbConnectionStringBuilder.TryGetValue("provider", out var providerValue)) { // Provider was overriden by ConnectionString providerName = providerValue.ToString(); } // ConnectionString was overriden by ConnectionString :) ConnectionString = SimpleLayout.Escape(connectionStringValue.ToString()); } } catch (Exception ex) { InternalLogger.Warn(ex, "DbConnectionStringBuilder failed to parse ConnectionString"); } } #if !NETSTANDARD if (string.IsNullOrEmpty(providerName)) { foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows) { var invariantname = (string)row["InvariantName"]; if (invariantname == DBProvider) { providerName = DBProvider; break; } } } if (!string.IsNullOrEmpty(providerName)) { ProviderFactory = DbProviderFactories.GetFactory(providerName); foundProvider = true; } #endif if (!foundProvider) { SetConnectionType(); } }