private LoggingConfiguration CreatePerTestConfiguration(MethodInfo methodUnderTest) { var newConfig = new LoggingConfiguration(); var fileTarget = new FileTarget { FileName = "${basedir}\\" + TestsDirName + "\\" + GenerateTestFileName(methodUnderTest), Layout = Layout.FromString("${longdate} ${logger} ${level} ${mdc:item=database} ${threadid} ${message} ${exception:format=tostring}"), Name = "DynamicFile" }; // tweak async target: // - increase batch size to avoid frequent and small disk writes // - don't discard messages if overflow var asyncTarget = new AsyncTargetWrapper(fileTarget, 20000, AsyncTargetWrapperOverflowAction.Block) { Name = "DynamicAsync", BatchSize = 2000 }; newConfig.AddTarget(asyncTarget); newConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Debug, asyncTarget)); return(newConfig); }
public void AsyncTargetWrapperExceptionTest() { var targetWrapper = new AsyncTargetWrapper { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 500, WrappedTarget = new DebugTarget(), Name = "AsyncTargetWrapperExceptionTest_Wrapper" }; using (new NoThrowNLogExceptions()) { targetWrapper.Initialize(null); // null out wrapped target - will cause exception on the timer thread targetWrapper.WrappedTarget = null; string internalLog = RunAndCaptureInternalLog( () => { targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); targetWrapper.Close(); }, LogLevel.Trace); Assert.True(internalLog.Contains("WrappedTarget is NULL"), internalLog); } }
/// <summary> /// Adds the file target. /// </summary> /// <param name="path">The path.</param> /// <param name="level">The level.</param> private void AddFileTarget(string path, LogSeverity level) { DebugFileWriter( LogDirectory, String.Format( "AddFileTarget called, path = [{0}], level = [{1}].", path, level.ToString() )); RemoveTarget("ApplicationLogFileWrapper"); var wrapper = new AsyncTargetWrapper(); wrapper.Name = "ApplicationLogFileWrapper"; var logFile = new FileTarget { FileName = path, Layout = "${longdate} ${level} ${logger}: ${message}" }; logFile.Name = "ApplicationLogFile"; wrapper.WrappedTarget = logFile; AddLogTarget(wrapper, level); }
public Target GetTarget(Action <SentryNLogOptions> customConfig = null, bool asyncTarget = false) { var options = Options; if (customConfig != null) { options = new SentryNLogOptions(); customConfig(options); } Target target = new SentryTarget( options, HubAccessor, SdkDisposeHandle, Clock) { Name = "sentry", Dsn = ValidDsnWithoutSecret, }; if (asyncTarget) { target = new AsyncTargetWrapper(target) { Name = "sentry_async" }; } return(target); }
public void WrapperRefTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='c' type='Debug' layout='${message}' /> <wrapper name='a' type='AsyncWrapper'> <target-ref name='c' /> </wrapper> <wrapper-target name='b' type='BufferingWrapper' bufferSize='19'> <wrapper-target-ref name='a' /> </wrapper-target> </targets> </nlog>"); 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 AsyncTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget); targetWrapper.Initialize(null); myTarget.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne()); Assert.Null(lastException); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); }
public void FlushingMultipleTimesSimultaneous() { var asyncTarget = new AsyncTargetWrapper { TimeToSleepBetweenBatches = 2000, WrappedTarget = new DebugTarget(), }; asyncTarget.Initialize(null); asyncTarget.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); var firstContinuationCalled = false; var secondContinuationCalled = false; var firstContinuationResetEvent = new ManualResetEvent(false); var secondContinuationResetEvent = new ManualResetEvent(false); asyncTarget.Flush(ex => { firstContinuationCalled = true; firstContinuationResetEvent.Set(); }); asyncTarget.Flush(ex => { secondContinuationCalled = true; secondContinuationResetEvent.Set(); }); firstContinuationResetEvent.WaitOne(); secondContinuationResetEvent.WaitOne(); Assert.True(firstContinuationCalled); Assert.True(secondContinuationCalled); }
public void NoEmptyEventLists() { var target = new MyLogReceiverWebServiceTarget(); target.EndpointAddress = "http://notimportant:9999/"; var logger = new LogFactory().Setup().LoadConfiguration(cfg => { var asyncTarget = new AsyncTargetWrapper(target) { Name = "NoEmptyEventLists_wrapper" }; cfg.Configuration.AddRuleForAllLevels(asyncTarget); }).GetLogger("logger1"); try { logger.Info("message1"); Thread.Sleep(1000); Assert.Equal(1, target.SendCount); } finally { logger.Factory.Shutdown(); } }
public void AsyncTargetWrapperCloseTest() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var targetWrapper = new AsyncTargetWrapper(myTarget) { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 1000, }; targetWrapper.Initialize(null); myTarget.Initialize(null); bool continuationHit = false; targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { continuationHit = true; })); // quickly close the target before the timer elapses targetWrapper.Close(); // continuation will not be hit because the thread is down. Thread.Sleep(1000); Assert.IsFalse(continuationHit); }
private static ILogger GetLog() { var config = new NLog.Config.LoggingConfiguration(); var fileTarget = new FileTarget("logfile") { FileName = LogPath, ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, KeepFileOpen = true, ConcurrentWrites = false, AutoFlush = false, OpenFileFlushTimeout = 1, }; var asyncFileTarget = new AsyncTargetWrapper(fileTarget) { TimeToSleepBetweenBatches = 0, OverflowAction = AsyncTargetWrapperOverflowAction.Block, BatchSize = 500, }; var logTarget = new ColoredConsoleTarget("logconsole"); #if DEBUG config.AddRule(LogLevel.Trace, LogLevel.Fatal, logTarget, "default"); // only echo messages from default logger to the console #else config.AddRule(LogLevel.Info, LogLevel.Fatal, logTarget, "default"); #endif config.AddRule(LogLevel.Debug, LogLevel.Fatal, asyncFileTarget); LogManager.Configuration = config; return(LogManager.GetLogger("default")); }
private static void Configure() { if (configured) { return; } lock (configureLock) { if (configured) { return; } string directory = Path.GetDirectoryName(LogFile); Directory.CreateDirectory(directory); FileTarget target = new FileTarget(); target.FileName = LogFile; target.ArchiveNumbering = ArchiveNumberingMode.Rolling; target.ArchiveEvery = FileArchivePeriod.None; target.ArchiveAboveSize = 10485760; AsyncTargetWrapper wrapper = new AsyncTargetWrapper(target, 5000, AsyncTargetWrapperOverflowAction.Discard); LogManager.Configuration = new NLog.Config.LoggingConfiguration(); LogManager.Configuration.AddTarget("file", wrapper); LoggingRule fileRule = new LoggingRule("*", NLogLevel, wrapper); LogManager.Configuration.LoggingRules.Add(fileRule); LogManager.ReconfigExistingLoggers(); } }
public static LoggingConfiguration GenerateTransmissionLoggingConfig(LoggingConfiguration config, int archiveFiles) { var transmissionFileTarget = new FileTarget { FileName = @"${date:format=yyyy-MM-dd}-transmissionlog.csv", ArchiveFileName = @"${basedir}/TransmissionLogArchive/{#}-transmissionlog.old.csv", ArchiveNumbering = ArchiveNumberingMode.Date, MaxArchiveFiles = archiveFiles, ArchiveEvery = FileArchivePeriod.Day, Layout = @"${longdate}, ${message}" }; var transmissionWrapper = new AsyncTargetWrapper(transmissionFileTarget, 5000, AsyncTargetWrapperOverflowAction.Discard); config.AddTarget("asyncTransmissionFileTarget", transmissionWrapper); var transmissionRule = new LoggingRule( "Ciribob.DCS.SimpleRadio.Standalone.Server.Network.Models.TransmissionLoggingQueue", LogLevel.Info, transmissionWrapper ); transmissionRule.Final = true; config.LoggingRules.Add(transmissionRule); return(config); }
private void ConfigLogger() { logWindow = new NLog.Windows.Forms.RichTextBoxTarget { Name = "LogWindow", Layout = "${date:format=yyyy.MM.dd HH.mm.ss} ${threadname:padding=-6} ${threadid:padding=-2} ${pad:padding=-7:inner=[${level:uppercase=True}]}: ${message}${onexception:inner=${literal:text=\\:} ${exception:innerformat=Message:maxInnerExceptionLevel=10:innerExceptionSeparator=-->:format=Message}}", ControlName = "logRichTextBox", FormName = "Form1", AutoScroll = true, MaxLines = 500, UseDefaultRowColoringRules = true }; maxLinesTextBox.Text = logWindow.MaxLines.ToString(); guiWrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper() { Name = "GUI", OverflowAction = NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Discard, BatchSize = 10, QueueLimit = 500, FullBatchSizeWriteLimit = 1, TimeToSleepBetweenBatches = 400, WrappedTarget = logWindow }; timeToSleepBetweenBatchesTextBox.Text = guiWrapper.TimeToSleepBetweenBatches.ToString(); overflowActionComboBox.Items.AddRange(Enum.GetNames(typeof(AsyncTargetWrapperOverflowAction))); overflowActionComboBox.SelectedIndex = (int)guiWrapper.OverflowAction; queueLimitTextBox.Text = guiWrapper.QueueLimit.ToString(); fullBatchSizeWriteLimitTextBox.Text = guiWrapper.FullBatchSizeWriteLimit.ToString(); batchSizeTextBox.Text = guiWrapper.BatchSize.ToString(); LogManager.Configuration.AddTarget(guiWrapper.Name, guiWrapper); LogManager.Configuration.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, guiWrapper)); LogManager.ReconfigExistingLoggers(); }
public static void InitNlog() { var configNLog = new LoggingConfiguration(); var targetFile = new FileTarget(); var targetFolder = AppDomain.CurrentDomain.BaseDirectory; targetFile.FileName = targetFolder + "/logs/${shortdate}.log"; targetFile.Layout = "[${date:format=dd.MM.yyyy HH\\:mm\\:ss.fff}] [${level:uppercase=true} ${logger}]: ${message}"; targetFile.ArchiveFileName = "${basedir}/logs/archives/${shortdate}.zip"; targetFile.ArchiveEvery = FileArchivePeriod.Day; targetFile.EnableArchiveFileCompression = true; targetFile.MaxArchiveFiles = 20; targetFile.ArchiveAboveSize = 104857600; //100 Mb AsyncTargetWrapper asyncWrapperF = new AsyncTargetWrapper { Name = "AsyncFile", WrappedTarget = targetFile }; configNLog.AddTarget(asyncWrapperF); var ruleFile = new LoggingRule("*", LogLevel.Trace, targetFile); configNLog.LoggingRules.Add(ruleFile); LogManager.Configuration = configNLog; Logger = LogManager.GetCurrentClassLogger(); // Logger.Info("Logger started."); }
public static Logger SetupLogger() { LoggingConfiguration config = new LoggingConfiguration(); // ### FILE ### FileTarget logfile = new FileTarget() { FileName = string.Format(Path.Combine("logs", "{0}_{1}.txt"), typeof(Program).Namespace, DateTime.Now.ToString("yyyyMMdd.HHmmss")), Name = "logfile", KeepFileOpen = true, ConcurrentWrites = false, Encoding = Encoding.UTF8 }; AsyncTargetWrapper asyncfile = new AsyncTargetWrapper(logfile, 512, AsyncTargetWrapperOverflowAction.Grow); // ### CONSOLE ### ColoredConsoleTarget logconsole = new ColoredConsoleTarget() { Name = "logconsole", DetectConsoleAvailable = true }; config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, logconsole)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, asyncfile)); NLog.LogManager.Configuration = config; return(NLog.LogManager.GetCurrentClassLogger()); }
public void WrapperRefTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='c' type='Debug' layout='${message}' /> <wrapper name='a' type='AsyncWrapper'> <target-ref name='c' /> </wrapper> <wrapper-target name='b' type='BufferingWrapper' bufferSize='19'> <wrapper-target-ref name='a' /> </wrapper-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("a")); Assert.NotNull(c.FindTargetByName("b")); Assert.NotNull(c.FindTargetByName("c")); Assert.IsType <BufferingTargetWrapper>(c.FindTargetByName("b")); Assert.IsType <AsyncTargetWrapper>(c.FindTargetByName("a")); Assert.IsType <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.Same(atw, btw.WrappedTarget); Assert.Same(dt, atw.WrappedTarget); Assert.Equal(19, btw.BufferSize); }
static Log() { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget("target1") { Layout = @"${date:format=HH\:mm\:ss} | ${level} | ${message} | ${exception}" }; config.AddTarget(consoleTarget); var errorTarget = new FileTarget("ErrorLog") { FileName = "${basedir}/logs/${shortdate}.log", Layout = "${longdate} | ${level} | Message: ${message} | Exception: ${exception:format=ToString,Stacktrace}${newline}" }; var infoTarget = new FileTarget("InfoTarget") { FileName = "${basedir}/logs/${shortdate}.log", Layout = "${longdate} | ${level} | Message: ${message}" }; var errorWrapper = new AsyncTargetWrapper(errorTarget, 5000, AsyncTargetWrapperOverflowAction.Discard); var infoWrapper = new AsyncTargetWrapper(infoTarget, 5000, AsyncTargetWrapperOverflowAction.Discard); config.AddTarget("ErrorWrapper", errorWrapper); config.AddTarget("InfoWrapper", infoWrapper); config.AddRuleForOneLevel(LogLevel.Info, "InfoWrapper"); config.AddRuleForOneLevel(LogLevel.Error, "ErrorWrapper"); config.AddRuleForOneLevel(LogLevel.Debug, "InfoWrapper"); config.AddRuleForAllLevels(consoleTarget); LogManager.Configuration = config; }
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 AsyncTargetWrapperExceptionTest() { var targetWrapper = new AsyncTargetWrapper { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 500, WrappedTarget = new DebugTarget(), }; targetWrapper.Initialize(null); // null out wrapped target - will cause exception on the timer thread targetWrapper.WrappedTarget = null; string internalLog = RunAndCaptureInternalLog( () => { targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); Thread.Sleep(1000); }, LogLevel.Trace); targetWrapper.Close(); Assert.True(internalLog.StartsWith("Error Error in lazy writer timer procedure: System.NullReferenceException", StringComparison.Ordinal), internalLog); }
protected override void CreateLogger() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget { Name = "FileTarget", FileName = tempFile, KeepFileOpen = true, ConcurrentWrites = false, AutoFlush = false, Layout = "${message}" }; var asyncFileTarget = new AsyncTargetWrapper(fileTarget) { TimeToSleepBetweenBatches = 0, OverflowAction = AsyncTargetWrapperOverflowAction.Block, BatchSize = 100 }; config.AddTarget("file", asyncFileTarget); config.AddRuleForAllLevels(asyncFileTarget); LogManager.Configuration = config; LogManager.ReconfigExistingLoggers(); _logger = LogManager.GetCurrentClassLogger(); }
private static void InitializeLogging() { var config = new LoggingConfiguration(); Target debuggerTarget = new DebuggerTarget() { Layout = "${longdate}|${level}|${logger}|${message} ${exception:format=tostring}" }; Target consoleTarget = new ColoredConsoleTarget() { Layout = "${longdate}|${level}|${logger}|${message} ${exception:format=tostring}" }; #if !DEBUG || TRUE debuggerTarget = new AsyncTargetWrapper(debuggerTarget); consoleTarget = new AsyncTargetWrapper(consoleTarget); #else new AsyncTargetWrapper().Wrap(); // Placeholder for optimizing imports #endif config.AddTarget("debugger", debuggerTarget); config.AddTarget("console", consoleTarget); var debuggerRule = new LoggingRule("*", LogLevel.Debug, debuggerTarget); config.LoggingRules.Add(debuggerRule); var consoleRule = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(consoleRule); LogManager.Configuration = config; }
public static void InstantiateRLogger() { var target = new RichTextBoxTarget { Name = "RichTextBox", Layout = "${longdate:useUTC=true} | ${level:uppercase=true} | ${logger} :: ${message}", ControlName = "textbox1", FormName = "Form1", AutoScroll = true, Height = 480, Width = 640, MaxLines = 10000, UseDefaultRowColoringRules = false }; target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Trace", "DarkGray", "Control")); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Control")); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "ControlText", "Control")); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "DarkRed", "Control")); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed")); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed")); var asyncWrapper = new AsyncTargetWrapper { Name = "AsyncRichTextBox", WrappedTarget = target }; SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace); }
public void NoEmptyEventLists() { var configuration = new LoggingConfiguration(); var target = new MyLogReceiverWebServiceTarget(); target.EndpointAddress = "http://notimportant:9999/"; target.Initialize(configuration); var asyncTarget = new AsyncTargetWrapper(target) { Name = "NoEmptyEventLists_wrapper" }; try { asyncTarget.Initialize(configuration); asyncTarget.WriteAsyncLogEvents(new[] { LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(ex => { }) }); Thread.Sleep(1000); Assert.Equal(1, target.SendCount); } finally { asyncTarget.Close(); target.Close(); } }
private void MainWindowInitialized(object sender, EventArgs e) { // Set Log Target // https://nlog.codeplex.com/workitem/6272 /*var target = new WpfRichTextBoxTarget * { * Name = ConsoleTargetName, * Layout = "${time:}|${threadid:padding=3}|${level:uppercase=true:padding=-5}|${logger:padding=-15}|${message}|${exception}", * ControlName = TextLog.Name, * FormName = Name, * AutoScroll = true, * MaxLines = 100000, * UseDefaultRowColoringRules = true * }; * _wrapper = new AsyncTargetWrapper * { * Name = ConsoleTargetName, * WrappedTarget = target * };*/ //SimpleConfigurator.ConfigureForTargetLogging(_wrapper, LogLevel.Trace); this.TextLog.Document.PageWidth = 1000; this.Dispatcher.Invoke( () => { var target = new WpfRichTextBoxTarget { Name = "RichText", Layout = //"[${longdate:useUTC=false}] :: [${level:uppercase=true}] :: ${logger}:${callsite} :: ${message} ${exception:innerFormat=tostring:maxInnerExceptionLevel=10:separator=,:format=tostring}", "${date:format=MM-dd-yyyy HH\\:mm\\:ss} [${uppercase:${level}}] ${message}", ControlName = this.TextLog.Name, FormName = this.GetType().Name, AutoScroll = true, MaxLines = 100000, UseDefaultRowColoringRules = true }; var asyncWrapper = new AsyncTargetWrapper { Name = "RichTextAsync", WrappedTarget = target }; LogManager.Configuration.AddTarget(asyncWrapper.Name, asyncWrapper); LogManager.Configuration.LoggingRules.Insert(0, new LoggingRule("*", LogLevel.Debug, asyncWrapper)); LogManager.ReconfigExistingLoggers(); }); /*Logger.Log(LogLevel.Info, "The time is: {0}", DateTime.Now); * Logger.Log(LogLevel.Error, "The time is: {0}", DateTime.Now); * Logger.Log(LogLevel.Debug, "The time is: {0}", DateTime.Now); * Logger.Log(LogLevel.Trace, "The time is: {0}", DateTime.Now); * Logger.Log(LogLevel.Warn, "The time is: {0}", DateTime.Now); * //Logger.Log(LogLevel.Off, "The time is: {0}", DateTime.Now);*/ this.Logger.Info(string.Format("The time is: {0}", DateTime.Now)); this.Logger.Error(string.Format("The time is: {0}", DateTime.Now)); this.Logger.Debug(string.Format("The time is: {0}", DateTime.Now)); this.Logger.Warn(string.Format("The time is: {0}", DateTime.Now)); //Logger.Log(LogLevel.Off, "The time is: {0}", DateTime.Now); }
public static void ConfigureOptimizedSimpleFileLogger(ThreadingType threadingType) { var logFileName = $"{Parameters.RootLogsDirectory}\\NLog.{threadingType}.Optimized.SimpleFile.log"; File.Delete(logFileName); var config = new LoggingConfiguration(); var simpleLogFileTarget = new FileTarget("SimpleLogFileTarget") { FileName = logFileName, Layout = LogOutputTemplate, KeepFileOpen = true, // Improves performance drastically (by default is set to false) }; var asyncTargetWrapper = new AsyncTargetWrapper() { Name = "AsyncTargetWrapper", BatchSize = 50, FullBatchSizeWriteLimit = 1, OptimizeBufferReuse = true, OverflowAction = AsyncTargetWrapperOverflowAction.Grow, QueueLimit = 10000, TimeToSleepBetweenBatches = 0, WrappedTarget = simpleLogFileTarget }; config.AddTarget(asyncTargetWrapper); config.AddRule(LogLevel.Info, LogLevel.Fatal, asyncTargetWrapper); LogManager.Configuration = config; }
public NLogLoggingConfiguration Setup() { Ensure.NotEmpty(_logFolderPath, nameof(_logFolderPath)); Ensure.NotEmpty(_prefix, nameof(_prefix)); var config = new LoggingConfiguration(); var fileTarget = new AsyncTargetWrapper("file", _fileTarget = new FileTarget { FileName = $"{_logFolderPath}/{_prefix}.txt", Layout = "${longdate} ${level:uppercase=true} ${message} ${exception:format=tostring}", Encoding = Encoding.UTF8, KeepFileOpen = true, ConcurrentWrites = false, OptimizeBufferReuse = true, OpenFileCacheTimeout = 30, ArchiveEvery = FileArchivePeriod.Day, ArchiveAboveSize = 490000, ArchiveFileName = $"{_logFolderPath}/{_prefix}.{{#}}.txt", ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, MaxArchiveFiles = 30, ArchiveDateFormat = "yyyy-MM-dd" }); config.AddTarget(fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); LogManager.Configuration = config; return(this); }
/* * Changes to the logging configuration in this method must be replicated in * this VS project's NLog.config file */ private void SetupLogging() { // If there is a configuration file then this will already be set if (LogManager.Configuration != null) { loggingReady = true; return; } var config = new LoggingConfiguration(); var fileTarget = new FileTarget { FileName = "clientlog.txt", ArchiveFileName = "clientlog.old.txt", MaxArchiveFiles = 1, ArchiveAboveSize = 104857600, Layout = @"${longdate} | ${logger} | ${message} ${exception:format=toString,Data:maxInnerExceptionLevel=1}" }; var wrapper = new AsyncTargetWrapper(fileTarget, 5000, AsyncTargetWrapperOverflowAction.Discard); config.AddTarget("asyncFileTarget", wrapper); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, wrapper)); LogManager.Configuration = config; loggingReady = true; Logger = LogManager.GetCurrentClassLogger(); }
public static void WriteErrorLog(string message) { FileTarget target = new FileTarget(); target.Layout = "${longdate} ${logger} ${message}"; target.FileName = "${basedir}/Trace/ChemInformLog.txt"; target.KeepFileOpen = false; target.Encoding = "iso-8859-2"; AsyncTargetWrapper wrapper = new AsyncTargetWrapper(); wrapper.WrappedTarget = target; wrapper.QueueLimit = 5000; wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Discard; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, NLog.LogLevel.Trace); Logger logger = LogManager.GetLogger(GlobalVariables.ProjectName); logger.Trace(message); try { ApplicationError appError = new ApplicationError(); appError.UserName = GlobalVariables.UserName; appError.RoleName = GlobalVariables.RoleName; appError.AppError = message; CommonDB.SaveApplicationErrors(appError); } catch { } }
public void AddConsoleOutput() { DebugFileWriter( LogDirectory, String.Format( "AddConsoleOutput called." )); RemoveTarget("ConsoleTargetWrapper"); var wrapper = new AsyncTargetWrapper(); wrapper.Name = "ConsoleTargetWrapper"; var target = new ConsoleTarget() { Layout = "${level}, ${logger}, ${message}", Error = false }; target.Name = "ConsoleTarget"; wrapper.WrappedTarget = target; AddLogTarget(wrapper, LogSeverity); }
private void SetupLogging() { // If there is a configuration file then this will already be set if (LogManager.Configuration != null) { loggingReady = true; return; } var config = new LoggingConfiguration(); var fileTarget = new FileTarget { FileName = "serverlog.txt", ArchiveFileName = "serverlog.old.txt", MaxArchiveFiles = 1, ArchiveAboveSize = 104857600, Layout = @"${longdate} | ${logger} | ${message} ${exception:format=toString,Data:maxInnerExceptionLevel=1}" }; var wrapper = new AsyncTargetWrapper(fileTarget, 5000, AsyncTargetWrapperOverflowAction.Discard); config.AddTarget("asyncFileTarget", wrapper); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, wrapper)); // only add transmission logging at launch if its enabled, defer rule and target creation otherwise if (ServerSettingsStore.Instance.GetGeneralSetting(ServerSettingsKeys.TRANSMISSION_LOG_ENABLED).BoolValue) { config = LoggingHelper.GenerateTransmissionLoggingConfig(config, ServerSettingsStore.Instance.GetGeneralSetting(ServerSettingsKeys.TRANSMISSION_LOG_RETENTION).IntValue); } LogManager.Configuration = config; loggingReady = true; }