public LoggingConfiguration(IProgram program, IOperatingSystem os, IVSServices vsservice) { NLog.Config.LoggingConfiguration conf; string assemblyFolder = program.ExecutingAssemblyDirectory; try { conf = new XmlLoggingConfiguration(Path.Combine(assemblyFolder, "NLog.config"), true); } catch (Exception ex) { vsservice.ActivityLogError(string.Format(CultureInfo.InvariantCulture, "Error loading nlog.config. {0}", ex)); conf = new NLog.Config.LoggingConfiguration(); } var fileTarget = conf.FindTargetByName("file") as FileTarget; if (fileTarget == null) { fileTarget = new FileTarget(); conf.AddTarget(Path.GetRandomFileName(), fileTarget); conf.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget)); } fileTarget.FileName = Path.Combine(os.Environment.GetLocalGitHubApplicationDataPath(), "extension.log"); fileTarget.Layout = layout; try { LogManager.Configuration = conf; } catch (Exception ex) { vsservice.ActivityLogError(string.Format(CultureInfo.InvariantCulture, "Error configuring the log. {0}", ex)); } }
public static void LoadConfig() { Assembly assembly = Assembly.GetExecutingAssembly(); Stream logconfigStream = assembly.GetManifestResourceStream("FinaChanCore.Log.NLog.cfg.xml"); XmlReader xr = XmlReader.Create(logconfigStream); XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null); LogManager.Configuration = config; }
static void ConfigNLogFromString(string appConfig) { var nlogText = XDocument.Parse(appConfig) .Descendants() .First(x => x.Name == "nlog") .ToString(); var config = new XmlLoggingConfiguration(new XmlTextReader(new StringReader(nlogText)), null); LogManager.Configuration = config; }
/// <summary> /// Initializes the specified configuration files, we only use the first found one /// </summary> /// <param name="configFiles">All the potential configuration files, order by priority.</param> /// <returns></returns> public override bool Initialize(string[] configFiles) { if (!base.Initialize(configFiles)) return false; m_DefaultConfig = new XmlLoggingConfiguration(ConfigFile) { AutoReload = true }; m_DefaultLogFactory = new NLogRef.LogFactory(m_DefaultConfig); return true; }
public void OutputTest() { var config = new XmlLoggingConfiguration("NLog.Targets.ElasticSearch.Tests.dll.config"); LogManager.Configuration = config; var logger = LogManager.GetLogger("Example"); logger.Trace("trace log message"); logger.Debug("debug log message: {0}", 1); logger.Info("info log message"); logger.Warn("warn log message"); logger.Error("error log message"); logger.Fatal("fatal log message"); }
private void ConfigureLogging() { string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); LogFileName = Path.Combine(assemblyFolder, "NLog.config"); var config = new NLog.Config.XmlLoggingConfiguration(LogFileName); LogManager.Configuration = config; var targets = config.AllTargets; if (targets != null && targets.Any() && targets.First() is FileTarget) { LogFileName = ((FileTarget)targets.First()).FileName.Render(new LogEventInfo()); } }
public MdlcLayoutRendererTests() { ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("mdlc", typeof(MdlcLayoutRenderer)); const string configXml = @" <nlog> <targets><target name='debug' type='Debug' layout='${mdlc:Item=myitem}${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"; var element = XElement.Parse(configXml); var config = new XmlLoggingConfiguration(element.CreateReader(), null); LogManager.Configuration = config; _target = LogManager.Configuration.FindTargetByName("debug") as DebugTarget; MappedDiagnosticsLogicalContext.Clear(); }
public void SimpleTest() { XmlDocument doc = new XmlDocument(); doc.LoadXml(@" <nlog> <targets> <target name='d' type='Debug' layout='${message}' /> </targets> </nlog>"); LoggingConfiguration c = new XmlLoggingConfiguration(doc.DocumentElement, null); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.IsNotNull(t); Assert.AreEqual(t.Name, "d"); Assert.AreEqual("${message}", t.Layout); Layout l = t.CompiledLayout as Layout; Assert.IsNotNull(l); Assert.AreEqual(1, l.Renderers.Length); Assert.IsInstanceOfType(typeof(MessageLayoutRenderer), l.Renderers[0]); }
public void OutputTest() { var config = new XmlLoggingConfiguration("NLog.Targets.ElasticSearch.Tests.dll.config"); LogManager.Configuration = config; var logger = LogManager.GetLogger("Example"); GlobalDiagnosticsContext.Set("test", null); logger.Trace("trace log message"); logger.Debug("debug log message: {0}", 1); logger.Info("info log message"); GlobalDiagnosticsContext.Set("test", "hi"); logger.Warn("warn log message"); logger.Error("error log message"); logger.Fatal("fatal log message"); var ev = new LogEventInfo(); ev.TimeStamp = DateTime.Now; ev.Level = LogLevel.Error; ev.Message = "log with property"; ev.Properties["hello"] = new TestData { Val1 = "hello" }; logger.Log(ev); Thread.Sleep(500); }
static int Main(string[] args) { try { using (var context = new InstallationContext()) { context.LogOutput = Console.Out; XmlLoggingConfiguration configuration = null; bool uninstallMode = false; for (int i = 0; i < args.Length; ++i) { switch (args[i]) { case "-q": context.LogOutput = TextWriter.Null; break; case "-consolelog": context.LogOutput = Console.Out; break; case "-loglevel": context.LogLevel = LogLevel.FromString(args[++i]); break; case "-i": context.IgnoreFailures = true; break; case "-log": context.LogOutput = File.CreateText(args[++i]); break; case "-p": string arg = args[++i]; int p = arg.IndexOf('='); if (p < 0) { Console.WriteLine("Parameter '{0}' must be NAME=VALUE", arg); Usage(); return 1; } string paramName = arg.Substring(0, p); string paramValue = arg.Substring(p + 1); context.Parameters.Add(paramName, paramValue); break; case "-u": uninstallMode = true; break; case "-?": Usage(); return 0; default: if (args[i].StartsWith("-")) { Usage(); return 1; } configuration = new XmlLoggingConfiguration(args[i]); break; } } if (configuration == null) { Usage(); return 1; } if (uninstallMode) { configuration.Uninstall(context); } else { configuration.Install(context); } return 0; } } catch (Exception ex) { Console.WriteLine("EXCEPTION: {0}", ex); return 1; } }
private void AddCustomFilters(string defaultLoggerNamePattern, LoggingRule defaultRule) { DebugFileWriter( LogDirectory, String.Format( "AddCustomFilters called, defaultLoggerNamePattern = [{0}], defaultRule.LoggerNamePattern = [{1}].", defaultLoggerNamePattern, defaultRule.LoggerNamePattern )); try { var customConfig = new NLog.Config.XmlLoggingConfiguration(NLogConfigurationFilePath); DebugFileWriter( LogDirectory, String.Format( "Custom Configuration Loaded, Rule Count = [{0}].", customConfig.LoggingRules.Count.ToString() )); foreach (var customRule in customConfig.LoggingRules) { DebugFileWriter( LogDirectory, String.Format( "Read Custom Rule, LoggerNamePattern = [{0}], Targets = [{1}].", customRule.LoggerNamePattern, string.Join(",", customRule.Targets.Select(x => x.Name).ToList()) )); if (customRule.LoggerNamePattern.Equals(defaultLoggerNamePattern)) { if (customRule.Targets.Any((arg) => arg.Name.Equals(defaultRule.Targets.First().Name))) { DebugFileWriter( LogDirectory, String.Format( "Custom rule filters can be applied to this target, Filter Count = [{0}].", customRule.Filters.Count.ToString() )); foreach (ConditionBasedFilter customFilter in customRule.Filters) { DebugFileWriter( LogDirectory, String.Format( "Read Custom Filter, Filter = [{0}], Action = [{1}], Type = [{2}].", customFilter.Condition.ToString(), customFilter.Action.ToString(), customFilter.GetType().ToString() )); defaultRule.Filters.Add(customFilter); } } else { DebugFileWriter( LogDirectory, String.Format( "Ignoring custom rule as [Target] does not match." )); } } else { DebugFileWriter( LogDirectory, String.Format( "Ignoring custom rule as [LoggerNamePattern] does not match." )); } } } catch (Exception ex) { // Intentionally do nothing, prevent issues affecting normal execution. DebugFileWriter( LogDirectory, String.Format( "Exception in AddCustomFilters, ex.Message = [{0}].", ex.Message ) ); } }
public void Auto_Reload_invalidxml_test() { try { string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); var tempPathFile = Path.Combine(tempPath, "main.nlog"); WriteToFile(validXML, tempPathFile); //event for async testing var counterEvent = new CountdownEvent(1); var xmlLoggingConfiguration = new XmlLoggingConfiguration(tempPathFile); LogManager.Configuration = xmlLoggingConfiguration; LogManager.ConfigurationReloaded += SignalCounterEvent1(counterEvent); Test_if_reload_success(@"c:\temp\log.txt"); //set invalid, set valid WriteToFile(invalidXML, tempPathFile); counterEvent.Wait(5000); if (counterEvent.CurrentCount != 0) { throw new Exception("failed to reload"); } LogManager.ConfigurationReloaded -= SignalCounterEvent1(counterEvent); var counterEvent2 = new CountdownEvent(1); LogManager.ConfigurationReloaded += (sender, e) => SignalCounterEvent(counterEvent2); WriteToFile(validXML2, tempPathFile); counterEvent2.Wait(5000); if (counterEvent2.CurrentCount != 0) { throw new Exception("failed to reload - 2"); } Test_if_reload_success(@"c:\temp\log2.txt"); } finally { LogManager.Configuration = null; } }
public void Auto_reload_validxml_test() { try { string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); var tempPathFile = Path.Combine(tempPath, "main.nlog"); WriteToFile(validXML, tempPathFile); //event for async testing var counterEvent = new CountdownEvent(1); var xmlLoggingConfiguration = new XmlLoggingConfiguration(tempPathFile); LogManager.Configuration = xmlLoggingConfiguration; LogManager.ConfigurationReloaded += (sender, e) => { if(counterEvent.CurrentCount < 1) counterEvent.Signal(); }; Test_if_reload_success(@"c:\temp\log.txt"); WriteToFile(validXML2, tempPathFile); //test after signal counterEvent.Wait(3000); Test_if_reload_success(@"c:\temp\log2.txt"); } finally { LogManager.Configuration = null; } }
public void Auto_Reload_after_rename() { try { var tempFolder = Guid.NewGuid().ToString(); var newFileName = "other.config"; string tempPath = Path.Combine(Path.GetTempPath(), tempFolder); Directory.CreateDirectory(tempPath); var originalFileName = "main.nlog"; var originalFilePath = Path.Combine(tempPath, originalFileName); var newFilePath = Path.Combine(tempPath, newFileName); //delete old stuff new FileInfo(originalFilePath).Delete(); new FileInfo(newFilePath).Delete(); WriteToFile(GetValidXml(), originalFilePath); //event for async testing var counterEvent = new CountdownEvent(1); var xmlLoggingConfiguration = new XmlLoggingConfiguration(originalFilePath); LogManager.Configuration = xmlLoggingConfiguration; LogManager.ConfigurationReloaded += SignalCounterEvent1(counterEvent); //"move" var fileInfo = new FileInfo(originalFilePath); fileInfo.CopyTo(newFilePath); fileInfo.Delete(); Thread.Sleep(1000); //write to new file WriteToFile(GetValidXml(@"c:\temp\log2.txt"), newFilePath); //"move" back. var fileInfo2 = new FileInfo(newFilePath); fileInfo2.CopyTo(originalFilePath); fileInfo2.Delete(); counterEvent.Wait(5000); Thread.Sleep(1000); Test_if_reload_success(@"c:\temp\log2.txt"); if (counterEvent.CurrentCount != 0) { throw new Exception("failed to reload"); } } finally { LogManager.Configuration = null; } }
public void Auto_reload_validxml_test() { try { string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); var tempPathFile = Path.Combine(tempPath, "main.nlog"); string targetLogFile = Path.Combine(tempPath, @"log.txt"); WriteToFile(GetValidXml(targetLogFile), tempPathFile); //event for async testing var counterEvent = new CountdownEvent(1); var xmlLoggingConfiguration = new XmlLoggingConfiguration(tempPathFile); LogManager.Configuration = xmlLoggingConfiguration; LogManager.ConfigurationReloaded += (sender, e) => { if (counterEvent.CurrentCount < 1) counterEvent.Signal(); }; Test_if_reload_success(targetLogFile); string targetLogFile2 = Path.Combine(tempPath, @"log2.txt"); WriteToFile(GetValidXml(targetLogFile2), tempPathFile); //test after signal counterEvent.Wait(3000); //we need some extra time for completion Thread.Sleep(1000); Test_if_reload_success(targetLogFile2); } finally { LogManager.Configuration = null; } }
/// <summary> /// Initialize the logging environment for Azure; including /// automatically rewriting log file paths for compatibility with /// local storage and setting up private variables. /// </summary> public void InitializeForCloud() { // Attach the diagnostic monitor trace listener to the list of master // System.Diagnostics trace listeners Trace.Listeners.Clear(); if (RoleEnvironment.IsAvailable) Trace.Listeners.Add(new DiagnosticMonitorTraceListener()); else Trace.Listeners.Add(new DefaultTraceListener()); Trace.WriteLine("Initializing NLog configuration for Azure"); // Replace log file and role name settings in the configuration var currentCfg = LogManager.Configuration; if (currentCfg == null) { // Depending on the deployment environment (i.e. Azure emulator) the NLog library // may not properly auto-load the NLog.config file. var binDirectory = new Uri( Path.GetDirectoryName( Assembly.GetExecutingAssembly().GetName().CodeBase)).LocalPath; var configFile = Path.Combine(binDirectory, "NLog.config"); // Check for NLog.config in the local directory. if (File.Exists(configFile)) { var newConfig = new XmlLoggingConfiguration(configFile); LogManager.Configuration = newConfig; currentCfg = LogManager.Configuration; } else { // Set basic configuration and log the error var localPath = Path.GetTempPath(); var logDirPath = Path.Combine(localPath, "logs"); SimpleConfigurator.ConfigureForFileLogging( Path.Combine(logDirPath, "ApplicationLog.log")); Trace.TraceWarning( "Warning: no NLog configuration section found in web.config or NLog.config; falling back to basic configuration"); return; } } Trace.WriteLine("Resetting NLog configuration"); UpdateConfigForCloud(currentCfg); LogManager.Configuration = currentCfg; }
public void WrapperTest() { XmlDocument doc = new XmlDocument(); doc.LoadXml(@" <nlog> <targets> <target name='b' type='BufferingWrapper' bufferSize='19'> <target name='a' type='AsyncWrapper'> <target name='c' type='Debug' layout='${message}' /> </target> </target> </targets> </nlog>"); LoggingConfiguration c = new XmlLoggingConfiguration(doc.DocumentElement, null); Assert.IsNotNull(c.FindTargetByName("a")); Assert.IsNotNull(c.FindTargetByName("b")); Assert.IsNotNull(c.FindTargetByName("c")); Assert.IsInstanceOfType(typeof(BufferingTargetWrapper), c.FindTargetByName("b")); Assert.IsInstanceOfType(typeof(AsyncTargetWrapper), c.FindTargetByName("a")); Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("c")); BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper; AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper; DebugTarget dt = c.FindTargetByName("c") as DebugTarget; Assert.AreSame(atw, btw.WrappedTarget); Assert.AreSame(dt, atw.WrappedTarget); Assert.AreEqual(19, btw.BufferSize); }
public void CompoundTest() { XmlDocument doc = new XmlDocument(); doc.LoadXml(@" <nlog> <targets> <target name='rr' type='RoundRobinGroup'> <target name='d1' type='Debug' layout='${message}1' /> <target name='d2' type='Debug' layout='${message}2' /> <target name='d3' type='Debug' layout='${message}3' /> <target name='d4' type='Debug' layout='${message}4' /> </target> </targets> </nlog>"); LoggingConfiguration c = new XmlLoggingConfiguration(doc.DocumentElement, null); Assert.IsNotNull(c.FindTargetByName("rr")); Assert.IsNotNull(c.FindTargetByName("d1")); Assert.IsNotNull(c.FindTargetByName("d2")); Assert.IsNotNull(c.FindTargetByName("d3")); Assert.IsNotNull(c.FindTargetByName("d4")); Assert.IsInstanceOfType(typeof(RoundRobinTarget), c.FindTargetByName("rr")); Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d1")); Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d2")); Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d3")); Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d4")); RoundRobinTarget rr = c.FindTargetByName("rr") as RoundRobinTarget; DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget; DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget; DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget; DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget; Assert.AreEqual(4, rr.Targets.Count); Assert.AreSame(d1, rr.Targets[0]); Assert.AreSame(d2, rr.Targets[1]); Assert.AreSame(d3, rr.Targets[2]); Assert.AreSame(d4, rr.Targets[3]); Assert.AreEqual(d1.Layout, "${message}1"); Assert.AreEqual(d2.Layout, "${message}2"); Assert.AreEqual(d3.Layout, "${message}3"); Assert.AreEqual(d4.Layout, "${message}4"); }