public 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 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.Trace, debuggerTarget); config.LoggingRules.Add(debuggerRule); var consoleRule = new LoggingRule("*", LogLevel.Trace, consoleTarget); config.LoggingRules.Add(consoleRule); LogManager.Configuration = config; }
public void AsyncTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget); ((ISupportsInitialize)targetWrapper).Initialize(); ((ISupportsInitialize)myTarget).Initialize(); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteLogEvent(logEvent, continuation); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteLogEvent(logEvent, continuation); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(2, myTarget.WriteCount); }
private static Logger SetupNLog(NLogConfigurationApi config) { var logDirectory = string.IsNullOrEmpty(config.LogDirectory) ? "${basedir}/Logs" : config.LogDirectory; var fileTarget = new FileTarget { Name = "FileTarget", Layout = "${message}", ConcurrentWrites = false, FileName = new SimpleLayout(Path.Combine(logDirectory, "current.log")), ArchiveEvery = config.ArchivePeriod, ArchiveNumbering = ArchiveNumberingMode.Sequence, MaxArchiveFiles = config.MaxArchiveFiles, ArchiveFileName = new SimpleLayout(Path.Combine(logDirectory,"archive/{####}.log")) }; var asyncWrapper = new AsyncTargetWrapper(fileTarget) { Name = "AsyncWrapper" }; var loggingConfiguration = new LoggingConfiguration(); loggingConfiguration.AddTarget(LoggerName, asyncWrapper); loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LevelToNLogLevel(config.MinimumLogLevel), asyncWrapper)); LogManager.Configuration = loggingConfiguration; return LogManager.GetLogger(LoggerName); }
public void ConfigureNlog(Logger logger) { FileTarget target = new FileTarget(); target.FileName = "${basedir}\\logs\\ICtrl.Log_${date:format=ddMMyyyy}.txt"; target.KeepFileOpen = false; target.Encoding = "windows-1251"; target.Layout = "${date:format=HH\\:mm\\:ss.fff}|${level:padding=5:uppercase=true}|${message}"; AsyncTargetWrapper wrapper = new AsyncTargetWrapper(); wrapper.WrappedTarget = target; wrapper.QueueLimit = 5000; wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; logOn = GetLogLevel(); switch (logOn) { case 1: NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Info); break; default: NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Off); break; } }
public void AsyncTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperAsyncTest1_Wrapper" }; 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 AsyncTargetWrapperInitTest() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget, 300, AsyncTargetWrapperOverflowAction.Grow); Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, targetWrapper.OverflowAction); Assert.Equal(300, targetWrapper.QueueLimit); Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches); Assert.Equal(100, targetWrapper.BatchSize); }
private Target WrapWithAsyncTarget(Target t) { NLog.Targets.Wrappers.AsyncTargetWrapper atw = new NLog.Targets.Wrappers.AsyncTargetWrapper(); atw.WrappedTarget = t; atw.Name = t.Name; t.Name = t.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", atw.Name, t.Name); return(atw); }
private static Target CreateRavenDbTarget(IDependencyResolver dependencyResolver, LoggingConfiguration loggingConfiguration) { var documentStore = (IDocumentStore)dependencyResolver.GetService(typeof(IDocumentStore)); var ravenDbTarget = new RavenDbTarget(documentStore); var asyncWrapper = new AsyncTargetWrapper(ravenDbTarget, 1000, AsyncTargetWrapperOverflowAction.Discard); loggingConfiguration.AddTarget("ravenDb", asyncWrapper); return asyncWrapper; }
public void AsyncTargetWrapperInitTest_WhenTimeToSleepBetweenBatchesIsEqualToZero_ShouldThrowNLogConfigurationException() { LogManager.ThrowConfigExceptions = true; var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, TimeToSleepBetweenBatches = 0, }; Assert.Throws<NLogConfigurationException>(() => targetWrapper.Initialize(null)); }
public void AsyncTargetWrapperInitTest2() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, }; Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, targetWrapper.OverflowAction); Assert.Equal(10000, targetWrapper.QueueLimit); Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches); Assert.Equal(100, targetWrapper.BatchSize); }
public IEnumerable<NLog.Targets.Target> GetTargets() { foreach (var target in this.targetConfigurations) { var asyncTargetWrapper = new AsyncTargetWrapper() { Name = target.Id.ToString(), WrappedTarget = target.Type.GetConstructor(new Type[] { }).Invoke(null) as Target, BatchSize = 1 }; yield return asyncTargetWrapper; } }
protected virtual NLogLogger InitLogger() { var wrapper = new AsyncTargetWrapper { Name = typeof (AsyncTargetWrapper).Name, QueueLimit = 10000, WrappedTarget = LoadTarget(), OverflowAction = AsyncTargetWrapperOverflowAction.Grow }; SimpleConfigurator.ConfigureForTargetLogging(wrapper); LogManager.Configuration.LoggingRules.ForEachItem(lr => lr.EnableLoggingForLevel(LogLevel.Trace)); LogManager.ReconfigExistingLoggers(); return LogManager.GetLogger(LoggerName); }
public LogService(Model m) { LoggingConfiguration config = LogManager.Configuration; target = new LogServiceTarget(m.Messages); target.Layout = "${level}=> ${message} ${exception:format=Message} ${exception:format=Type} ${exception:format=StackTrace}"; target.Name = "LogService"; var wrapper = new AsyncTargetWrapper(target); config.AddTarget("LogService", wrapper); rule = new LoggingRule("*", LogLevel.Trace, target); config.LoggingRules.Add(rule); LogManager.Configuration = config; if (Debugger.IsAttached) target.Filter = LogLevel.Debug; }
static void Main(string[] args) { FileTarget target = new FileTarget(); target.Layout = "${longdate} ${logger} ${message}"; target.FileName = "${basedir}/logs/logfile.txt"; target.KeepFileOpen = false; target.Encoding = Encoding.UTF8; AsyncTargetWrapper wrapper = new AsyncTargetWrapper(); wrapper.WrappedTarget = target; wrapper.QueueLimit = 5000; wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Discard; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); }
private void ConfigureCaptureTarget() { captureTarget = new CaptureTarget { Layout = "${date}|${level:uppercase=true}|${logger}|${message}${onexception:inner=${newline}${exception:format=tostring}}" }; captureTarget.LogReceived += target_LogReceived; var asyncWrapper = new AsyncTargetWrapper { Name = "CaptureTargetWrapper", WrappedTarget = captureTarget }; LogManager.Configuration.AddTarget(asyncWrapper.Name, asyncWrapper); currentLogLevel = NLog.LogLevel.Info; loggingRule = new LoggingRule("*", currentLogLevel, asyncWrapper); LogManager.Configuration.LoggingRules.Insert(0, loggingRule); LogManager.ReconfigExistingLoggers(); PropertyChanged += OnPropertyChanged; #if DEBUG DebugEnabled = true; #endif }
public void Initialize(string logFilesDirectory) { var config = new LoggingConfiguration(); this.logfile = new FileTarget(); var logfilename = Path.Combine(logFilesDirectory, "${date:format=yyyy-MM-dd}.txt"); logfile.FileName = logfilename; logfile.CreateDirs = true; logfile.MaxArchiveFiles = 7; logfile.ArchiveEvery = FileArchivePeriod.Day; logfile.ConcurrentWrites = true; logfile.Layout = "${longdate}|${level:uppercase=true}|thread:${threadid}|${logger}|${message}${onexception:inner=${newline}${exception:format=tostring}}"; var asyncTarget = new AsyncTargetWrapper(logfile) { OverflowAction = AsyncTargetWrapperOverflowAction.Grow }; config.AddTarget("logfile", asyncTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, asyncTarget)); //#if DEBUG // var tracelogfile = new FileTarget(); // tracelogfile.FileName = Path.Combine(logFilesDirectory, "${date:format=yyyy-MM-dd}_Trace.txt"); // tracelogfile.CreateDirs = true; // tracelogfile.MaxArchiveFiles = 7; // tracelogfile.ArchiveEvery = FileArchivePeriod.Day; // tracelogfile.ConcurrentWrites = true; // tracelogfile.Layout = // "${longdate}|${level:uppercase=true}|thread:${threadid}|${logger}|${message}${onexception:inner=${newline}${exception:format=tostring}}"; // var asyncTarget2 = new AsyncTargetWrapper(tracelogfile) // { // OverflowAction = AsyncTargetWrapperOverflowAction.Grow // }; // config.AddTarget("tracelogfile", asyncTarget2); // config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, asyncTarget2)); //#endif LogManager.Configuration = config; // Caliburn.Micro.LogManager.GetLog = type => new NLogger(type); }
/// <summary> /// Initializes the NLog logging configuration. /// </summary> /// <remarks> /// Using DLL injection, we can't place an Nlog.config file in our target directory, so we have to create the configuration during runtime. /// </remarks> public static void Initialize() { var config = new LoggingConfiguration(); var target = new FileTarget { FileName = "C:/Sc2Ai/Logs/Sc2AiBot.log", Layout = "${longdate} ${level} ${callsite} ${message}", DeleteOldFileOnStartup = true }; var targetWrapper = new AsyncTargetWrapper(target, Int32.MaxValue, AsyncTargetWrapperOverflowAction.Discard); config.AddTarget("File", targetWrapper); var rule = new LoggingRule("*", LogLevel.Trace, target); config.LoggingRules.Add(rule); LogManager.Configuration = config; //LogManager.DisableLogging(); }
private void InitializeLog() { var target = new WpfRichTextBoxTarget(Color.FromRgb(0, 0, 0)) { Name = "console", Layout = "${message}", ControlName = LogRitchTextBox.Name, FormName = Name, AutoScroll = true, MaxLines = 100000, UseDefaultRowColoringRules = true }; var asyncWrapper = new AsyncTargetWrapper { Name = "console", WrappedTarget = target }; SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, NLog.LogLevel.Debug); LogManager.Default = new Dicom.Log.NLogManager(); }
public void AsyncTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper { WrappedTarget = myTarget, }; targetWrapper.Initialize(null); myTarget.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; ManualResetEvent continuationHit = new ManualResetEvent(false); Thread continuationThread = null; AsyncContinuation continuation = ex => { lastException = ex; continuationThread = Thread.CurrentThread; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); // continuation was not hit Assert.True(continuationHit.WaitOne(2000)); Assert.NotSame(continuationThread, Thread.CurrentThread); Assert.Null(lastException); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotSame(continuationThread, Thread.CurrentThread); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); }
/// <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) { 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 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 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(3000); }, LogLevel.Trace); targetWrapper.Close(); Assert.True(internalLog.StartsWith("Error Error in lazy writer timer procedure: System.NullReferenceException", StringComparison.Ordinal), internalLog); }
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); targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); // quickly close the target before the timer elapses targetWrapper.Close(); }
public void AsyncTargetWrapperFlushTest() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var targetWrapper = new AsyncTargetWrapper(myTarget) { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, }; targetWrapper.Initialize(null); myTarget.Initialize(null); List<Exception> exceptions = new List<Exception>(); int eventCount = 5000; for (int i = 0; i < eventCount; ++i) { targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation( ex => { lock (exceptions) { exceptions.Add(ex); } })); } Exception lastException = null; ManualResetEvent mre = new ManualResetEvent(false); string internalLog = RunAndCaptureInternalLog( () => { targetWrapper.Flush( cont => { try { // by this time all continuations should be completed Assert.Equal(eventCount, exceptions.Count); // with just 1 flush of the target Assert.Equal(1, myTarget.FlushCount); // and all writes should be accounted for Assert.Equal(eventCount, myTarget.WriteCount); } catch (Exception ex) { lastException = ex; } finally { mre.Set(); } }); Assert.True(mre.WaitOne()); }, LogLevel.Trace); if (lastException != null) { Assert.True(false, lastException.ToString() + "\r\n" + internalLog); } }
public void AsyncTargetWrapperAsyncWithExceptionTest1() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; 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.NotNull(lastException); Assert.IsType(typeof(InvalidOperationException), lastException); // no flush on exception Assert.Equal(0, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); lastException = null; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotNull(lastException); Assert.IsType(typeof(InvalidOperationException), lastException); Assert.Equal(0, myTarget.FlushCount); Assert.Equal(2, myTarget.WriteCount); }
/// <summary> /// Configures NLOG to our needs /// Spawns a Debug Target as well as a "normal" Log Target /// </summary> /// <param name="appName">Name of the Application</param> /// <param name="logFileName">Name of the Logfile</param> /// <param name="logLevel"><see cref="System.LogLevel"/> to use</param> public static void ConfigureLogging(string appName, string logFileName, LogLevel logLevel, bool logPerformance, bool enableSqlTrace, bool enableDotNetTrace) { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var logTarget = new FileTarget { Encoding = Encoding.UTF8 }; config.AddTarget("log", logTarget); logTarget.FileName = logFileName; // debugTarget.Layout = @"[${date:format=yyyy\.MM\.dd HH\:mm\:ss}] [${level}] [${callsite:fileName=True:className=False:methodName=True:includeSourcePath=False}]: ${message} ${exception:format=Method,Message,StackTrace:separator=\n}"; logTarget.Layout = @"[${date:universalTime=true:format=u}]" + " [${processid:fixedLength=True:padding=5:padCharacter= }] [${threadid:fixedLength=True:padding=5:padCharacter= }] [${level:fixedLength=True:padding=5:padCharacter= :upperCase=True}] [${callsite:fileName=True:className=False:methodName=True:includeSourcePath=False:padding=35:padCharacter= }] ${message} ${exception:maxInnerExceptionLevel=3:format=Method,Message,StackTrace:innerFormat=Method,Message,StackTrace:separator=\r\n:innerExceptionSeparator=\r\n}"; logTarget.ArchiveAboveSize = 1024 * 1024 * 100; logTarget.MaxArchiveFiles = 10; logTarget.KeepFileOpen = true; // logTarget.Header = "\r\nTime\tProcessID\tThreadID\tLogLevel\tCallSite\tMessage/Exception"; logTarget.ConcurrentWrites = true; var logWrapper = new AsyncTargetWrapper { BatchSize = 500, WrappedTarget = logTarget, QueueLimit = 5000, OverflowAction = AsyncTargetWrapperOverflowAction.Block, TimeToSleepBetweenBatches = 250 }; var debugTarget = new FileTarget { Encoding = Encoding.UTF8 }; config.AddTarget("debug", debugTarget); var debugFileInfo = new FileInfo(logFileName); var directory = debugFileInfo.DirectoryName; var fileExtension = debugFileInfo.Extension; var fileName = debugFileInfo.Name; var fileNameNew = fileName.Substring(0, fileName.Length - fileExtension.Length); var fileNameNewFull = Path.Combine(directory, fileNameNew + ".errors." + fileExtension); debugTarget.FileName = fileNameNewFull; // debugTarget.Layout = @"[${date:format=yyyy\.MM\.dd HH\:mm\:ss}] [${level}] [${callsite:fileName=True:className=False:methodName=True:includeSourcePath=False}]: ${message} ${exception:format=Method,Message,StackTrace:separator=\n}"; debugTarget.Layout = @"[${date:universalTime=true:format=u}]" + " [${processid:fixedLength=True:padding=5:padCharacter= }] [${threadid:fixedLength=True:padding=5:padCharacter= }] [${level:fixedLength=True:padding=5:padCharacter= :upperCase=True}] [${callsite:fileName=True:className=False:methodName=True:includeSourcePath=False:padding=35:padCharacter= }] ${message} ${exception:format=Method,Message,StackTrace:separator=\r\n}"; debugTarget.ArchiveAboveSize = 1024 * 1024 * 100; debugTarget.MaxArchiveFiles = 10; debugTarget.KeepFileOpen = true; debugTarget.Header = "\r\nTime\tProcessID\tThreadID\tLogLevel\tCallSite\tMessage/Exception"; debugTarget.ConcurrentWrites = true; var debugwrapper = new AsyncTargetWrapper { BatchSize = 500, WrappedTarget = debugTarget, QueueLimit = 5000, OverflowAction = AsyncTargetWrapperOverflowAction.Block, TimeToSleepBetweenBatches = 250 }; var performanceLevel = logPerformance ? logLevel : LogLevel.Off; var rule = new LoggingRule("VerboseTrace", performanceLevel, logWrapper) { Final = true }; var rule1 = new LoggingRule("*", logLevel, logWrapper); var rule2 = new LoggingRule("*", LogLevel.Error, debugwrapper); config.LoggingRules.Add(rule); config.LoggingRules.Add(rule1); config.LoggingRules.Add(rule2); // Step 5. Activate the configuration LogManager.Configuration = config; // Get Assembly Version var myAssembly = Assembly.GetExecutingAssembly(); var myAssemblyName = myAssembly.GetName(); Logger.Info("{0} v{1}", appName, myAssemblyName.Version); Logger.Trace("Configured logging."); if (enableDotNetTrace || enableSqlTrace) { var listener = new NLogTraceListener(); listener.AutoLoggerName = true; listener.DefaultLogLevel = logLevel; Trace.Listeners.Add(listener); } if (enableSqlTrace) { SD.LLBLGen.Pro.ORMSupportClasses.TraceHelper.PersistenceExecutionSwitch.Level = TraceLevel.Verbose; } AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; }
private static Target WrapWithAsyncTargetWrapper(Target target) { var asyncTargetWrapper = new AsyncTargetWrapper(); asyncTargetWrapper.WrappedTarget = target; asyncTargetWrapper.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name); target = asyncTargetWrapper; return target; }
public void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero() { LogManager.ThrowConfigExceptions = true; var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, TimeToSleepBetweenBatches = 0, BatchSize = 4, QueueLimit = 2, // Will make it "sleep" between every second write OverflowAction = AsyncTargetWrapperOverflowAction.Block }; targetWrapper.Initialize(null); myTarget.Initialize(null); try { int flushCounter = 0; AsyncContinuation flushHandler = (ex) => { ++flushCounter; }; List<KeyValuePair<LogEventInfo, AsyncContinuation>> itemPrepareList = new List<KeyValuePair<LogEventInfo, AsyncContinuation>>(2500); List<int> itemWrittenList = new List<int>(itemPrepareList.Capacity); for (int i = 0; i< itemPrepareList.Capacity; ++i) { var logEvent = new LogEventInfo(); int sequenceID = logEvent.SequenceID; itemPrepareList.Add(new KeyValuePair<LogEventInfo, AsyncContinuation>(logEvent, (ex) => itemWrittenList.Add(sequenceID))); } long startTicks = Environment.TickCount; for (int i = 0; i < itemPrepareList.Count; ++i) { var logEvent = itemPrepareList[i].Key; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(itemPrepareList[i].Value)); } targetWrapper.Flush(flushHandler); for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i) System.Threading.Thread.Sleep(1); long elapsedMilliseconds = Environment.TickCount - startTicks; Assert.Equal(itemPrepareList.Count, itemWrittenList.Count); int prevSequenceID = 0; for (int i = 0; i < itemWrittenList.Count; ++i) { Assert.True(prevSequenceID < itemWrittenList[i]); prevSequenceID = itemWrittenList[i]; } #if MONO || NET3_5 Assert.True(elapsedMilliseconds < 2500); // Skip timing test when running within OpenCover.Console.exe #endif targetWrapper.Flush(flushHandler); for (int i = 0; i < 2000 && flushCounter != 2; ++i) System.Threading.Thread.Sleep(1); Assert.Equal(2, flushCounter); } finally { myTarget.Close(); targetWrapper.Close(); } }
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(); } }
public void AsyncTargetWrapperExceptionTest() { var targetWrapper = new AsyncTargetWrapper { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 500, WrappedTarget = new DebugTarget(), Name = "AsyncTargetWrapperExceptionTest_Wrapper" }; LogManager.ThrowExceptions = false; 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("AsyncWrapper 'AsyncTargetWrapperExceptionTest_Wrapper': WrappedTarget is NULL"), internalLog); }
public void AddConsoleOutput() { 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); }