public static void Initialize () { if (!Initialized) { logger = new InternalLogger (); LoggingService.AddLogger (logger); } }
public static void Dispose () { if (Initialized) { LoggingService.RemoveLogger (logger.Name); logger = null; } }
private void RunInstallCommands(InstallationContext installationContext, IEnumerable <DatabaseCommandInfo> commands) { // create log event that will be used to render all layouts LogEventInfo logEvent = installationContext.CreateLogEvent(); try { foreach (var commandInfo in commands) { string cs; if (commandInfo.ConnectionString != null) { // if there is connection string specified on the command info, use it cs = commandInfo.ConnectionString.Render(logEvent); } else if (this.InstallConnectionString != null) { // next, try InstallConnectionString cs = this.InstallConnectionString.Render(logEvent); } else { // if it's not defined, fall back to regular connection string cs = this.BuildConnectionString(logEvent); } this.EnsureConnectionOpen(cs); var command = this.activeConnection.CreateCommand(); command.CommandType = commandInfo.CommandType; command.CommandText = commandInfo.Text.Render(logEvent); try { installationContext.Trace("Executing {0} '{1}'", command.CommandType, command.CommandText); command.ExecuteNonQuery(); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures) { installationContext.Warning(exception.Message); } else { installationContext.Error(exception.Message); throw; } } } } finally { InternalLogger.Trace("DatabaseTarget: close connection after install."); this.CloseConnection(); } }
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 AutoReloadTest() { if (IsMacOsX()) { // skip this on Mac OS, since it requires root permissions for // filesystem watcher return; } using (new InternalLoggerScope()) { string fileName = Path.GetTempFileName(); try { _reloadCounter = 0; LogManager.ConfigurationReloaded += OnConfigReloaded; using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } LogManager.Configuration = new XmlLoggingConfiguration(fileName); AssertDebugCounter("debug", 0); Logger logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); InternalLogger.Info("Rewriting test file..."); // now write the file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } InternalLogger.Info("Rewritten."); WaitForConfigReload(1); logger.Debug("aaa"); AssertDebugLastMessage("debug", "xxx aaa"); // write the file again, this time make an error using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(2); logger.Debug("bbb"); AssertDebugLastMessage("debug", "xxx bbb"); // write the corrected file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='zzz ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(3); logger.Debug("ccc"); AssertDebugLastMessage("debug", "zzz ccc"); } finally { LogManager.ConfigurationReloaded -= OnConfigReloaded; LogManager.Configuration = null; if (File.Exists(fileName)) { File.Delete(fileName); } } } }
private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory) { extensionsElement.AssertName("extensions"); var addElements = extensionsElement.Elements("add").ToList(); foreach (var addElement in addElements) { string prefix = addElement.GetOptionalAttribute("prefix", null); if (prefix != null) { prefix = prefix + "."; } string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null)); if (type != null) { this.ConfigurationItemFactory.RegisterType(Type.GetType(type, true), prefix); } string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null); if (assemblyFile != null) { try { #if SILVERLIGHT && !WINDOWS_PHONE var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else string fullFileName = Path.Combine(baseDirectory, assemblyFile); InternalLogger.Info("Loading assembly file: {0}", fullFileName); Assembly asm = Assembly.LoadFrom(fullFileName); #endif this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } InternalLogger.Error(exception, "Error loading extensions."); if (exception.MustBeRethrown()) { throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception); } } continue; } string assemblyName = addElement.GetOptionalAttribute("assembly", null); if (assemblyName != null) { try { InternalLogger.Info("Loading assembly name: {0}", assemblyName); #if SILVERLIGHT && !WINDOWS_PHONE var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else Assembly asm = Assembly.Load(assemblyName); #endif this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } InternalLogger.Error(exception, "Error loading extensions."); if (exception.MustBeRethrown()) { throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception); } } } } }
/// <summary> /// Parse {Logger} xml element /// </summary> /// <param name="loggerElement"></param> /// <param name="rulesCollection">Rules are added to this parameter.</param> private void ParseLoggerElement(NLogXmlElement loggerElement, IList <LoggingRule> rulesCollection) { loggerElement.AssertName("logger"); var namePattern = loggerElement.GetOptionalAttribute("name", "*"); var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true); if (!enabled) { InternalLogger.Debug("The logger named '{0}' are disabled"); return; } var rule = new LoggingRule(); string appendTo = loggerElement.GetOptionalAttribute("appendTo", null); if (appendTo == null) { appendTo = loggerElement.GetOptionalAttribute("writeTo", null); } rule.LoggerNamePattern = namePattern; if (appendTo != null) { foreach (string t in appendTo.Split(',')) { string targetName = t.Trim(); Target target = FindTargetByName(targetName); if (target != null) { rule.Targets.Add(target); } else { throw new NLogConfigurationException("Target " + targetName + " not found."); } } } rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false); string levelString; if (loggerElement.AttributeValues.TryGetValue("level", out levelString)) { LogLevel level = LogLevel.FromString(levelString); rule.EnableLoggingForLevel(level); } else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString)) { levelString = CleanSpaces(levelString); string[] tokens = levelString.Split(','); foreach (string token in tokens) { if (!string.IsNullOrEmpty(token)) { LogLevel level = LogLevel.FromString(token); rule.EnableLoggingForLevel(level); } } } else { int minLevel = 0; int maxLevel = LogLevel.MaxLevel.Ordinal; string minLevelString; string maxLevelString; if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString)) { minLevel = LogLevel.FromString(minLevelString).Ordinal; } if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString)) { maxLevel = LogLevel.FromString(maxLevelString).Ordinal; } for (int i = minLevel; i <= maxLevel; ++i) { rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i)); } } var children = loggerElement.Children.ToList(); foreach (var child in children) { switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "FILTERS": this.ParseFilters(rule, child); break; case "LOGGER": this.ParseLoggerElement(child, rule.ChildRules); break; } } rulesCollection.Add(rule); }
private NLogEvents TranslateLogEvents(AsyncLogEventInfo[] logEvents) { if (logEvents.Length == 0 && !LogManager.ThrowExceptions) { InternalLogger.Error("LogEvents array is empty, sending empty event..."); return(new NLogEvents()); } string clientID = string.Empty; if (this.ClientId != null) { clientID = this.ClientId.Render(logEvents[0].LogEvent); } var networkLogEvents = new NLogEvents { ClientName = clientID, LayoutNames = new StringCollection(), Strings = new StringCollection(), BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks }; var stringTable = new Dictionary <string, int>(); for (int i = 0; i < this.Parameters.Count; ++i) { networkLogEvents.LayoutNames.Add(this.Parameters[i].Name); } if (this.IncludeEventProperties) { for (int i = 0; i < logEvents.Length; ++i) { var ev = logEvents[i].LogEvent; if (ev.HasProperties) { // add all event-level property names in 'LayoutNames' collection. foreach (var prop in ev.Properties) { string propName = prop.Key as string; if (propName != null) { if (!networkLogEvents.LayoutNames.Contains(propName)) { networkLogEvents.LayoutNames.Add(propName); } } } } } } networkLogEvents.Events = new NLogEvent[logEvents.Length]; for (int i = 0; i < logEvents.Length; ++i) { networkLogEvents.Events[i] = this.TranslateEvent(logEvents[i].LogEvent, networkLogEvents, stringTable); } return(networkLogEvents); }
internal void ReloadConfigOnTimer(object state) { LoggingConfiguration configurationToReload = (LoggingConfiguration)state; InternalLogger.Info("Reloading configuration..."); lock (this.syncRoot) { if (this.reloadTimer != null) { this.reloadTimer.Dispose(); this.reloadTimer = null; } if (this.IsDisposing) { return; //timer was disposed already. } this.watcher.StopWatching(); try { if (this.Configuration != configurationToReload) { throw new NLogConfigurationException("Config changed in between. Not reloading."); } LoggingConfiguration newConfig = configurationToReload.Reload(); //problem: XmlLoggingConfiguration.Initialize eats exception with invalid XML. ALso XmlLoggingConfiguration.Reload never returns null. //therefor we check the InitializeSucceeded property. var xmlConfig = newConfig as XmlLoggingConfiguration; if (xmlConfig != null) { if (!xmlConfig.InitializeSucceeded.HasValue || !xmlConfig.InitializeSucceeded.Value) { throw new NLogConfigurationException("Configuration.Reload() failed. Invalid XML?"); } } if (newConfig != null) { this.Configuration = newConfig; if (this.ConfigurationReloaded != null) { this.ConfigurationReloaded(this, new LoggingConfigurationReloadedEventArgs(true, null)); } } else { throw new NLogConfigurationException("Configuration.Reload() returned null. Not reloading."); } } catch (Exception exception) { //special case, don't rethrow NLogConfigurationException if (exception is NLogConfigurationException) { InternalLogger.Warn(exception, "NLog configuration while reloading"); } else if (exception.MustBeRethrown()) { throw; } this.watcher.Watch(configurationToReload.FileNamesToWatch); var configurationReloadedDelegate = this.ConfigurationReloaded; if (configurationReloadedDelegate != null) { configurationReloadedDelegate(this, new LoggingConfigurationReloadedEventArgs(false, exception)); } } } }
private void LogConfigurationInitialized() { InternalLogger.Info("Configuration initialized."); InternalLogger.LogAssemblyVersion(typeof(ILogger).Assembly); }
private void LoadLoggingConfiguration(string configFile) { InternalLogger.Debug("Loading config from {0}", configFile); this.config = new XmlLoggingConfiguration(configFile, this); }
private Logger GetLogger(LoggerCacheKey cacheKey) { lock (this.syncRoot) { Logger existingLogger = loggerCache.Retrieve(cacheKey); if (existingLogger != null) { // Logger is still in cache and referenced. return(existingLogger); } Logger newLogger; if (cacheKey.ConcreteType != null && cacheKey.ConcreteType != typeof(Logger)) { var fullName = cacheKey.ConcreteType.FullName; try { //creating instance of static class isn't possible, and also not wanted (it cannot inherited from Logger) if (cacheKey.ConcreteType.IsStaticClass()) { var errorMessage = string.Format("GetLogger / GetCurrentClassLogger is '{0}' as loggerType can be a static class and should inherit from Logger", fullName); InternalLogger.Error(errorMessage); if (ThrowExceptions) { throw new NLogRuntimeException(errorMessage); } newLogger = CreateDefaultLogger(ref cacheKey); } else { var instance = FactoryHelper.CreateInstance(cacheKey.ConcreteType); newLogger = instance as Logger; if (newLogger == null) { //well, it's not a Logger, and we should return a Logger. var errorMessage = string.Format("GetLogger / GetCurrentClassLogger got '{0}' as loggerType which doesn't inherit from Logger", fullName); InternalLogger.Error(errorMessage); if (ThrowExceptions) { throw new NLogRuntimeException(errorMessage); } // Creating default instance of logger if instance of specified type cannot be created. newLogger = CreateDefaultLogger(ref cacheKey); } } } catch (Exception ex) { InternalLogger.Error(ex, "GetLogger / GetCurrentClassLogger. Cannot create instance of type '{0}'. It should have an default contructor. ", fullName); if (ex.MustBeRethrown()) { throw; } // Creating default instance of logger if instance of specified type cannot be created. newLogger = CreateDefaultLogger(ref cacheKey); } } else { newLogger = new Logger(); } if (cacheKey.ConcreteType != null) { newLogger.Initialize(cacheKey.Name, this.GetConfigurationForLogger(cacheKey.Name, this.Configuration), this); } // TODO: Clarify what is the intention when cacheKey.ConcreteType = null. // At the moment, a logger typeof(Logger) will be created but the ConcreteType // will remain null and inserted into the cache. // Should we set cacheKey.ConcreteType = typeof(Logger) for default loggers? loggerCache.InsertOrUpdate(cacheKey, newLogger); return(newLogger); } }
internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func <AsyncCallback, IAsyncResult> beginFunc, Func <IAsyncResult, Stream> getStreamFunc) { Stream postPayload = null; if (Protocol == WebServiceProtocol.HttpGet) { PrepareGetRequest(request); } else { postPayload = _postFormatterFactories[Protocol](this).PrepareRequest(request, parameters); } AsyncContinuation sendContinuation = ex => { if (ex != null) { continuation(ex); return; } request.BeginGetResponse( r => { try { using (var response = request.EndGetResponse(r)) { } continuation(null); } catch (Exception ex2) { InternalLogger.Error(ex2, "Error when sending to Webservice."); if (ex2.MustBeRethrown()) { throw; } continuation(ex2); } }, null); }; if (postPayload != null && postPayload.Length > 0) { postPayload.Position = 0; beginFunc( result => { try { using (Stream stream = getStreamFunc(result)) { WriteStreamAndFixPreamble(postPayload, stream, this.IncludeBOM, this.Encoding); postPayload.Dispose(); } sendContinuation(null); } catch (Exception ex) { postPayload.Dispose(); InternalLogger.Error(ex, "Error when sending to Webservice."); if (ex.MustBeRethrown()) { throw; } continuation(ex); } }); } else { sendContinuation(null); } }
private void ProcessPendingEvents(object state) { if (this.lazyWriterTimer == null) { return; } bool?wroteFullBatchSize = false; bool lockTaken = false; try { if (TimeToSleepBetweenBatches <= 0) { Monitor.Enter(this.timerLockObject); lockTaken = true; } int count = WriteEventsInQueue(this.BatchSize, "Timer"); if (count == 0) { wroteFullBatchSize = null; // Nothing to write } else if (count == BatchSize) { wroteFullBatchSize = true; } } catch (Exception exception) { wroteFullBatchSize = false; // Something went wrong, lets throttle retry InternalLogger.Error(exception, "AsyncWrapper '{0}': Error in lazy writer timer procedure.", this.Name); if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } } finally { if (TimeToSleepBetweenBatches <= 0 && wroteFullBatchSize == true) { this.StartInstantWriterTimer(); // Found full batch, fast schedule to take next batch (within lock to avoid pile up) } if (lockTaken) { Monitor.Exit(this.timerLockObject); } if (TimeToSleepBetweenBatches <= 0) { // If queue was not empty, then more might have arrived while writing the first batch // Uses throttled timer here, so we can process in batches (faster) if (wroteFullBatchSize == false) { this.StartLazyWriterTimer(); // Queue was not empty, more might have come (Skip expensive RequestQueue-check) } else if (!wroteFullBatchSize.HasValue) { if (this.RequestQueue.RequestCount > 0) { this.StartLazyWriterTimer(); // Queue was checked as empty, but now we have more } } } else { this.StartLazyWriterTimer(); } } }
public void IdentityTest1Async() { var oldPrincipal = Thread.CurrentPrincipal; try { ConfigurationItemFactory.Default.Targets .RegisterDefinition("CSharpEventTarget", typeof(CSharpEventTarget)); LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"<?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' internalLogLevel='Debug' throwExceptions='true' > <targets async='true'> <target name='target1' xsi:type='CSharpEventTarget' layout='${identity}' /> </targets> <rules> <logger name='*' writeTo='target1' /> </rules> </nlog> "); try { var continuationHit = new ManualResetEvent(false); string rendered = null; var threadId = Thread.CurrentThread.ManagedThreadId; var asyncThreadId = threadId; LogEventInfo lastLogEvent = null; var asyncTarget = LogManager.Configuration.FindTargetByName <AsyncTargetWrapper>("target1"); Assert.NotNull(asyncTarget); var target = asyncTarget.WrappedTarget as CSharpEventTarget; Assert.NotNull(target); target.BeforeWrite += (logevent, rendered1, asyncThreadId1) => { //clear in current thread before write Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("ANOTHER user", "type"), null); }; target.EventWritten += (logevent, rendered1, asyncThreadId1) => { rendered = rendered1; asyncThreadId = asyncThreadId1; lastLogEvent = logevent; continuationHit.Set(); }; Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("SOMEDOMAIN\\SomeUser", "CustomAuth"), new[] { "Role1", "Role2" }); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("test write"); Assert.True(continuationHit.WaitOne()); Assert.NotNull(lastLogEvent); //should be written in another thread. Assert.NotEqual(threadId, asyncThreadId); Assert.Equal("auth:CustomAuth:SOMEDOMAIN\\SomeUser", rendered); } finally { LogManager.Configuration.Close(); } } finally { InternalLogger.Reset(); Thread.CurrentPrincipal = oldPrincipal; } }
private void WriteToOutput(LogEventInfo logEvent, string message) { ConsoleColor oldForegroundColor = Console.ForegroundColor; ConsoleColor oldBackgroundColor = Console.BackgroundColor; bool didChangeForegroundColor = false, didChangeBackgroundColor = false; try { var matchingRule = GetMatchingRowHighlightingRule(logEvent); didChangeForegroundColor = IsColorChange(matchingRule.ForegroundColor, oldForegroundColor); if (didChangeForegroundColor) { Console.ForegroundColor = (ConsoleColor)matchingRule.ForegroundColor; } didChangeBackgroundColor = IsColorChange(matchingRule.BackgroundColor, oldBackgroundColor); if (didChangeBackgroundColor) { Console.BackgroundColor = (ConsoleColor)matchingRule.BackgroundColor; } try { var consoleStream = this.ErrorStream ? Console.Error : Console.Out; if (this.WordHighlightingRules.Count == 0) { consoleStream.WriteLine(message); } else { message = message.Replace("\a", "\a\a"); foreach (ConsoleWordHighlightingRule hl in this.WordHighlightingRules) { message = hl.ReplaceWithEscapeSequences(message); } ColorizeEscapeSequences(consoleStream, message, new ColorPair(Console.ForegroundColor, Console.BackgroundColor), new ColorPair(oldForegroundColor, oldBackgroundColor)); consoleStream.WriteLine(); didChangeForegroundColor = didChangeBackgroundColor = true; } } catch (IndexOutOfRangeException ex) { //this is a bug and therefor stopping logging. For docs, see PauseLogging property _pauseLogging = true; InternalLogger.Warn(ex, "An IndexOutOfRangeException has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets"); } catch (ArgumentOutOfRangeException ex) { //this is a bug and therefor stopping logging. For docs, see PauseLogging property _pauseLogging = true; InternalLogger.Warn(ex, "An ArgumentOutOfRangeException has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets"); } } finally { if (didChangeForegroundColor) { Console.ForegroundColor = oldForegroundColor; } if (didChangeBackgroundColor) { Console.BackgroundColor = oldBackgroundColor; } } }
private void ProcessSingleMailMessage(List <AsyncLogEventInfo> events) { try { LogEventInfo firstEvent = events[0].LogEvent; LogEventInfo lastEvent = events[events.Count - 1].LogEvent; // unbuffered case, create a local buffer, append header, body and footer var bodyBuffer = new StringBuilder(); if (this.Header != null) { bodyBuffer.Append(this.Header.Render(firstEvent)); if (this.AddNewLines) { bodyBuffer.Append("\n"); } } foreach (AsyncLogEventInfo eventInfo in events) { bodyBuffer.Append(this.Layout.Render(eventInfo.LogEvent)); if (this.AddNewLines) { bodyBuffer.Append("\n"); } } if (this.Footer != null) { bodyBuffer.Append(this.Footer.Render(lastEvent)); if (this.AddNewLines) { bodyBuffer.Append("\n"); } } using (var msg = new MailMessage()) { this.SetupMailMessage(msg, lastEvent); msg.Body = bodyBuffer.ToString(); if (msg.IsBodyHtml && ReplaceNewlineWithBrTagInHtml) { msg.Body = msg.Body.Replace(EnvironmentHelper.NewLine, "<br/>"); } using (ISmtpClient client = this.CreateSmtpClient()) { if (!UseSystemNetMailSettings) { ConfigureMailClient(lastEvent, client); } InternalLogger.Debug("Sending mail to {0} using {1}:{2} (ssl={3})", msg.To, client.Host, client.Port, client.EnableSsl); InternalLogger.Trace(" Subject: '{0}'", msg.Subject); InternalLogger.Trace(" From: '{0}'", msg.From.ToString()); client.Send(msg); foreach (var ev in events) { ev.Continuation(null); } } } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } foreach (var ev in events) { ev.Continuation(exception); } } }
public void WriteToConsoleOutTests() { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; using (var loggerScope = new InternalLoggerScope(true)) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsole = true; { StringWriter consoleOutWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleOutput(consoleOutWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, consoleOutWriter1); } // // Redirect the console output to another StringWriter. { StringWriter consoleOutWriter2 = new StringWriter() { NewLine = "\n" }; loggerScope.SetConsoleOutput(consoleOutWriter2); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, consoleOutWriter2); } //lambdas { StringWriter consoleOutWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleOutput(consoleOutWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn(() => "WWW"); InternalLogger.Error(() => "EEE"); InternalLogger.Fatal(() => "FFF"); InternalLogger.Trace(() => "TTT"); InternalLogger.Debug(() => "DDD"); InternalLogger.Info(() => "III"); TestWriter(expected, consoleOutWriter1); } } }
/// <summary> /// Parse {NLog} xml element. /// </summary> /// <param name="nlogElement"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseNLogElement(NLogXmlElement nlogElement, string filePath, bool autoReloadDefault) { InternalLogger.Trace("ParseNLogElement"); nlogElement.AssertName("nlog"); if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false)) { this.DefaultCultureInfo = CultureInfo.InvariantCulture; } #pragma warning disable 618 this.ExceptionLoggingOldStyle = nlogElement.GetOptionalBooleanAttribute("exceptionLoggingOldStyle", false); #pragma warning restore 618 bool autoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", autoReloadDefault); if (filePath != null) { this.fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload; } logFactory.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", logFactory.ThrowExceptions); logFactory.ThrowConfigExceptions = nlogElement.GetOptionalBooleanAttribute("throwConfigExceptions", logFactory.ThrowConfigExceptions); InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole); InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError); InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile); InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name)); #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ InternalLogger.LogToTrace = nlogElement.GetOptionalBooleanAttribute("internalLogToTrace", InternalLogger.LogToTrace); #endif InternalLogger.IncludeTimestamp = nlogElement.GetOptionalBooleanAttribute("internalLogIncludeTimestamp", InternalLogger.IncludeTimestamp); logFactory.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", logFactory.GlobalThreshold.Name)); var children = nlogElement.Children.ToList(); //first load the extensions, as the can be used in other elements (targets etc) var extensionsChilds = children.Where(child => child.LocalName.Equals("EXTENSIONS", StringComparison.InvariantCultureIgnoreCase)).ToList(); foreach (var extensionsChild in extensionsChilds) { this.ParseExtensionsElement(extensionsChild, Path.GetDirectoryName(filePath)); } //parse all other direct elements foreach (var child in children) { switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "EXTENSIONS": //already parsed break; case "INCLUDE": this.ParseIncludeElement(child, Path.GetDirectoryName(filePath), autoReloadDefault: autoReload); break; case "APPENDERS": case "TARGETS": this.ParseTargetsElement(child); break; case "VARIABLE": this.ParseVariableElement(child); break; case "RULES": this.ParseRulesElement(child, this.LoggingRules); break; case "TIME": this.ParseTimeElement(child); break; default: InternalLogger.Warn("Skipping unknown node: {0}", child.LocalName); break; } } }
public void ExceptionTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; var ex1 = new Exception("e1"); var ex2 = new Exception("e2", new Exception("inner")); var ex3 = new NLogConfigurationException("config error"); var ex4 = new NLogConfigurationException("config error", ex2); var ex5 = new PathTooLongException(); ex5.Data["key1"] = "value1"; Exception ex6 = null; const string prefix = " Exception: "; { string expected = "Warn WWW1" + prefix + ex1 + Environment.NewLine + "Error EEE1" + prefix + ex2 + Environment.NewLine + "Fatal FFF1" + prefix + ex3 + Environment.NewLine + "Trace TTT1" + prefix + ex4 + Environment.NewLine + "Debug DDD1" + prefix + ex5 + Environment.NewLine + "Info III1" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, "WWW1"); InternalLogger.Error(ex2, "EEE1"); InternalLogger.Fatal(ex3, "FFF1"); InternalLogger.Trace(ex4, "TTT1"); InternalLogger.Debug(ex5, "DDD1"); InternalLogger.Info(ex6, "III1"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW2" + prefix + ex1 + Environment.NewLine + "Error EEE2" + prefix + ex2 + Environment.NewLine + "Fatal FFF2" + prefix + ex3 + Environment.NewLine + "Trace TTT2" + prefix + ex4 + Environment.NewLine + "Debug DDD2" + prefix + ex5 + Environment.NewLine + "Info III2" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, () => "WWW2"); InternalLogger.Error(ex2, () => "EEE2"); InternalLogger.Fatal(ex3, () => "FFF2"); InternalLogger.Trace(ex4, () => "TTT2"); InternalLogger.Debug(ex5, () => "DDD2"); InternalLogger.Info(ex6, () => "III2"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW3" + prefix + ex1 + Environment.NewLine + "Error EEE3" + prefix + ex2 + Environment.NewLine + "Fatal FFF3" + prefix + ex3 + Environment.NewLine + "Trace TTT3" + prefix + ex4 + Environment.NewLine + "Debug DDD3" + prefix + ex5 + Environment.NewLine + "Info III3" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, "WWW3"); InternalLogger.Log(ex2, LogLevel.Error, "EEE3"); InternalLogger.Log(ex3, LogLevel.Fatal, "FFF3"); InternalLogger.Log(ex4, LogLevel.Trace, "TTT3"); InternalLogger.Log(ex5, LogLevel.Debug, "DDD3"); InternalLogger.Log(ex6, LogLevel.Info, "III3"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW4" + prefix + ex1 + Environment.NewLine + "Error EEE4" + prefix + ex2 + Environment.NewLine + "Fatal FFF4" + prefix + ex3 + Environment.NewLine + "Trace TTT4" + prefix + ex4 + Environment.NewLine + "Debug DDD4" + prefix + ex5 + Environment.NewLine + "Info III4" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, () => "WWW4"); InternalLogger.Log(ex2, LogLevel.Error, () => "EEE4"); InternalLogger.Log(ex3, LogLevel.Fatal, () => "FFF4"); InternalLogger.Log(ex4, LogLevel.Trace, () => "TTT4"); InternalLogger.Log(ex5, LogLevel.Debug, () => "DDD4"); InternalLogger.Log(ex6, LogLevel.Info, () => "III4"); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } } }
private void ParseTargetsElement(NLogXmlElement targetsElement) { targetsElement.AssertName("targets", "appenders"); bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false); NLogXmlElement defaultWrapperElement = null; var typeNameToDefaultTargetParameters = new Dictionary <string, NLogXmlElement>(); var children = targetsElement.Children.ToList(); foreach (var targetElement in children) { string name = targetElement.LocalName; string typeAttributeVal = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null)); switch (name.ToUpper(CultureInfo.InvariantCulture)) { case "DEFAULT-WRAPPER": defaultWrapperElement = targetElement; break; case "DEFAULT-TARGET-PARAMETERS": if (typeAttributeVal == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } typeNameToDefaultTargetParameters[typeAttributeVal] = targetElement; break; case "TARGET": case "APPENDER": case "WRAPPER": case "WRAPPER-TARGET": case "COMPOUND-TARGET": if (typeAttributeVal == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(typeAttributeVal); NLogXmlElement defaults; if (typeNameToDefaultTargetParameters.TryGetValue(typeAttributeVal, out defaults)) { this.ParseTargetElement(newTarget, defaults); } this.ParseTargetElement(newTarget, targetElement); if (asyncWrap) { newTarget = WrapWithAsyncTargetWrapper(newTarget); } if (defaultWrapperElement != null) { newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement); } InternalLogger.Info("Adding target {0}", newTarget); AddTarget(newTarget.Name, newTarget); break; } } }
public void WriteToStringWriterTests() { try { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, writer2); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, () => "WWW"); InternalLogger.Log(LogLevel.Error, () => "EEE"); InternalLogger.Log(LogLevel.Fatal, () => "FFF"); InternalLogger.Log(LogLevel.Trace, () => "TTT"); InternalLogger.Log(LogLevel.Debug, () => "DDD"); InternalLogger.Log(LogLevel.Info, () => "III"); TestWriter(expected, writer2); } } finally { InternalLogger.Reset(); } }
internal void ReloadConfigOnTimer(object state) { if (_reloadTimer == null && _isDisposing) { return; //timer was disposed already. } LoggingConfiguration oldConfig = (LoggingConfiguration)state; InternalLogger.Info("Reloading configuration..."); lock (_logFactory._syncRoot) { LoggingConfiguration newConfig; try { if (_isDisposing) { return; //timer was disposed already. } var currentTimer = _reloadTimer; if (currentTimer != null) { _reloadTimer = null; currentTimer.WaitForDispose(TimeSpan.Zero); } if (_logFactory._config != oldConfig) { InternalLogger.Warn("NLog Config changed in between. Not reloading."); return; } newConfig = oldConfig.ReloadNewConfig(); if (newConfig == null) { return; } } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } InternalLogger.Warn(exception, "NLog configuration failed to reload"); _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(false, exception)); return; } try { TryUnwatchConfigFile(); _logFactory.Configuration = newConfig; // Triggers LogFactory to call Activated(...) that adds file-watch again _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(true)); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } InternalLogger.Warn(exception, "NLog configuration reloaded, failed to be assigned"); _watcher.Watch(oldConfig.FileNamesToWatch); _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(false, exception)); } } }
public void Dispose() { TimeSource.Current = new FastLocalTimeSource(); InternalLogger.Reset(); }
internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) { if (targets == null) { return; } #if !NETCF bool needTrace = false; bool needTraceSources = false; int nst = targets.NeedsStackTrace; if (nst > 0) { needTrace = true; } if (nst > 1) { needTraceSources = true; } StackTrace stackTrace = null; if (needTrace && !logEvent.HasStackTrace) { int firstUserFrame = 0; stackTrace = new StackTrace(STACK_TRACE_SKIP_METHODS, needTraceSources); for (int i = 0; i < stackTrace.FrameCount; ++i) { System.Reflection.MethodBase mb = stackTrace.GetFrame(i).GetMethod(); if (mb.DeclaringType == loggerType) { firstUserFrame = i + 1; } else { if (firstUserFrame != 0) { break; } } } logEvent.SetStackTrace(stackTrace, firstUserFrame); } #endif for (TargetWithFilterChain awf = targets; awf != null; awf = awf.Next) { Target app = awf.Target; FilterResult result = FilterResult.Neutral; try { FilterCollection filterChain = awf.FilterChain; for (int i = 0; i < filterChain.Count; ++i) { Filter f = filterChain[i]; result = f.Check(logEvent); if (result != FilterResult.Neutral) { break; } } if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal)) { if (InternalLogger.IsDebugEnabled) { InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level); } if (result == FilterResult.IgnoreFinal) { return; } continue; } } catch (Exception ex) { InternalLogger.Error("FilterChain exception: {0}", ex); if (factory.ThrowExceptions) { throw; } else { continue; } } try { app.Write(logEvent); } catch (Exception ex) { InternalLogger.Error("Target exception: {0}", ex); if (factory.ThrowExceptions) { throw; } else { continue; } } if (result == FilterResult.LogFinal) { return; } } }
public void InfoWrite(string format, params object[] args) { InternalLogger.Debug(format, args); }
/// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected override void CloseTarget() { base.CloseTarget(); InternalLogger.Trace("DatabaseTarget: close connection because of CloseTarget"); this.CloseConnection(); }
public void ErrorWrite(string format, params object[] args) { InternalLogger.Error(format, args); }
public static void Initialize(bool enableInternalLogger = false, bool enableInternalDebugLogger = false) { InternalLogger.EnableLogger(enableInternalLogger, enableInternalDebugLogger); PlatformHelper.InitializeSingleton(new AndroidPlatformHelper()); AndroidHorizontalListViewRenderer.Initialize(); }
public void ErrorWrite(Exception exception) { InternalLogger.Error(exception.ToString()); }
/// <summary> /// Registers the specified layout type to the factory under a specified name. /// </summary> /// <param name="name">The name of the layout (e.g. <code>XML</code>, <code>CSV</code> or <code>HTML</code>)</param> /// <param name="t">The type of the new layout</param> /// <remarks> /// The name specified in the name parameter can then be used /// to reference layouts. /// </remarks> public static void AddLayout(string name, Type t) { InternalLogger.Trace("Registering layout {0} for type '{1}'", name, t.FullName); _name2type[name.ToLower()] = t; }
/// <summary> /// Reads all bytes from the serial port input buffer. /// </summary> /// <param name="waitTimeout">Whether read receive data after wait for timeout to expire or read on data received.</param> /// <param name="timeout">The number of milliseconds before a time-out occurs when a read operation does not finish.</param> /// <param name="throwOnError">true to throw any exception that occurs.-or- false to ignore any exception that occurs.</param> /// <returns>The byte array of received data.</returns> public byte[] ReadSync(bool waitTimeout = false, int timeout = 1000, bool throwOnError = false) { this.CheckDisposed(); byte[] result = new byte[0]; if (!this._isSendingSync) { if (this._serialPort == null || !this.Open()) { throw new IOException("The specified port could not be found or opened."); } if (timeout < 1) { timeout = 1; } try { if (waitTimeout) { Thread.Sleep(timeout); } else { int timeoutCount = 0; while (timeoutCount <= timeout) { if (this._serialPort.BytesToRead <= 0) { Thread.Sleep(1); } timeoutCount++; } } Thread.Sleep(1); if (this._serialPort.BytesToRead > 0) { result = new byte[this._serialPort.BytesToRead]; this._serialPort.Read(result, 0, result.Length); } } catch (Exception e) { InternalLogger.Log(e); if (throwOnError) { throw; } } } return(result); }