public void ImpersonatingWrapperTest()
        {
            CreateUserIfNotPresent();

            var wrapped = new MyTarget()
            {
                ExpectedUser = LocalMachineName + "\\" + NLogTestUser,
            };

            var wrapper = new ImpersonatingTargetWrapper()
            {
                UserName      = NLogTestUser,
                Password      = NLogTestUserPassword,
                Domain        = LocalMachineName,
                WrappedTarget = wrapped,
            };

            var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
            {
                cfg.Configuration.AddRuleForAllLevels(wrapper);
            }).LogFactory;

            var exceptions = new List <Exception>();

            wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.Single(exceptions);
            wrapper.WriteAsyncLogEvents(
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.Equal(4, exceptions.Count);
            wrapper.Flush(exceptions.Add);
            Assert.Equal(5, exceptions.Count);
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            logFactory.Shutdown();
        }
Beispiel #2
0
        public void FlushingMultipleTimesSimultaneous()
        {
            var asyncTarget = new AsyncTargetWrapper
            {
                TimeToSleepBetweenBatches = 1000,
                WrappedTarget             = new DebugTarget(),
                Name = "FlushingMultipleTimesSimultaneous_Wrapper"
            };

            asyncTarget.Initialize(null);

            try
            {
                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);
            }
            finally
            {
                asyncTarget.Close();
            }
        }
Beispiel #3
0
        public void CachedLayoutRendererWrapper()
        {
            SimpleLayout l = "${guid}";

            string s1 = l.Render(LogEventInfo.CreateNullEvent());
            string s2 = l.Render(LogEventInfo.CreateNullEvent());
            string s3;

            // normally GUIDs are never the same
            Assert.AreNotEqual(s1, s2);

            // but when you apply ${cached}, the guid will only be generated once
            l  = "${cached:${guid}:cached=true}";
            s1 = l.Render(LogEventInfo.CreateNullEvent());
            s2 = l.Render(LogEventInfo.CreateNullEvent());
            Assert.AreEqual(s1, s2);

            // calling Close() on Layout Renderer will reset the cached value
            l.Renderers[0].Close();
            s3 = l.Render(LogEventInfo.CreateNullEvent());
            Assert.AreNotEqual(s2, s3);

            // calling Initialize() on Layout Renderer will reset the cached value
            l.Renderers[0].Close();
            string s4 = l.Render(LogEventInfo.CreateNullEvent());

            Assert.AreNotEqual(s3, s4);

            // another way to achieve the same thing is using cached=true
            l  = "${guid:cached=true}";
            s1 = l.Render(LogEventInfo.CreateNullEvent());
            s2 = l.Render(LogEventInfo.CreateNullEvent());
            Assert.AreEqual(s1, s2);

            // another way to achieve the same thing is using cached=true
            l  = "${guid:cached=false}";
            s1 = l.Render(LogEventInfo.CreateNullEvent());
            s2 = l.Render(LogEventInfo.CreateNullEvent());
            Assert.AreNotEqual(s1, s2);
        }
Beispiel #4
0
        /// <summary>
        /// Initializes the target.
        /// </summary>
        protected override void InitializeTarget()
        {
            _cancelTokenSource = new CancellationTokenSource();

            _platform = _platform ?? Platform.Instance();
            string logId = LogId?.Render(LogEventInfo.CreateNullEvent());

            GaxPreconditions.CheckNotNullOrEmpty(logId, nameof(LogId));

            if (SendJsonPayload)
            {
                if (JsonConverter != null)
                {
                    // Use the function provided directly.
                    GaxPreconditions.CheckState(
                        string.IsNullOrWhiteSpace(JsonConverterTypeName) && string.IsNullOrWhiteSpace(JsonConverterMethodName),
                        $"{nameof(JsonConverterTypeName)} and {nameof(JsonConverterMethodName)} must not be set along with {nameof(JsonConverter)}.");
                    _jsonConvertFunction = JsonConverter;
                }
                else if (!string.IsNullOrWhiteSpace(JsonConverterTypeName) || !string.IsNullOrWhiteSpace(JsonConverterMethodName))
                {
                    // Use the method refered to by type-name and method-name.
                    GaxPreconditions.CheckState(
                        !string.IsNullOrWhiteSpace(JsonConverterTypeName) && !string.IsNullOrWhiteSpace(JsonConverterMethodName),
                        $"Either both or neither of {nameof(JsonConverterTypeName)} and {nameof(JsonConverterMethodName)} must be specified.");
                    _jsonConvertFunction = BuildAndVerifyJsonConverter();
                }
                else
                {
                    // Use default json.net based converter.
                    _jsonConvertFunction = BuildProtoConverter();
                }
            }

            ActivateLogIdAndResource(logId);

            _client = _client ?? BuildLoggingServiceClient();

            base.InitializeTarget();
        }
        public void TestAllPropertiesWhenActivityEmpty(ActivityTraceProperty property, bool empty)
        {
            bool orgThrowExceptions = LogManager.ThrowExceptions;

            try
            {
                LogManager.ThrowExceptions          = true;
                System.Diagnostics.Activity.Current = new System.Diagnostics.Activity(null).Start();
                System.Diagnostics.Activity.Current.SetStartTime(new DateTime(0, DateTimeKind.Utc));

                var logEvent = LogEventInfo.CreateNullEvent();

                ActivityTraceLayoutRenderer layoutRenderer = new ActivityTraceLayoutRenderer();
                layoutRenderer.Property = property;
                var result = layoutRenderer.Render(logEvent);
                Assert.True(string.IsNullOrEmpty(result) == empty);
            }
            finally
            {
                LogManager.ThrowExceptions = orgThrowExceptions;
            }
        }
        public void RenderProcessNameLayoutRenderer()
        {
            Layout layout = "${processname}";

            layout.Initialize(null);
            string actual = layout.Render(LogEventInfo.CreateNullEvent());

            layout.Close();


            Assert.NotNull(actual);
            Assert.True(actual.Length > 0, "actual.Length > 0");
            var lower = actual.ToLower();

            //lowercase
            var allowedProcessNames = new List <string> {
                "vstest.executionengine", "xunit", "mono-sgen", "dotnet", "testhost.x86", "testhost.x64"
            };

            Assert.True(allowedProcessNames.Any(p => lower.Contains(p)),
                        $"validating processname failed. Please add (if correct) '{actual}' to 'allowedProcessNames'");
        }
        public void LogEventGuidTest()
        {
            GuidLayoutRenderer layoutRenderer = new GuidLayoutRenderer()
            {
                GeneratedFromLogEvent = true
            };
            LogEventInfo logEvent1 = LogEventInfo.CreateNullEvent();
            string       newGuid11 = layoutRenderer.Render(logEvent1);
            string       newGuid12 = layoutRenderer.Render(logEvent1);

            Assert.True(!string.IsNullOrEmpty(newGuid11));
            Assert.True(!string.IsNullOrEmpty(newGuid12));
            Assert.Equal(newGuid11, newGuid12);
            LogEventInfo logEvent2 = LogEventInfo.CreateNullEvent();
            string       newGuid21 = layoutRenderer.Render(logEvent2);
            string       newGuid22 = layoutRenderer.Render(logEvent2);

            Assert.True(!string.IsNullOrEmpty(newGuid21));
            Assert.True(!string.IsNullOrEmpty(newGuid22));
            Assert.Equal(newGuid21, newGuid22);
            Assert.NotEqual(newGuid11, newGuid22);
        }
        public void DatabaseExceptionTest3()
        {
            MockDbConnection.ClearLog();
            var exceptions = new List <Exception>();

            var db = new DatabaseTarget();

            db.CommandText      = "not important";
            db.ConnectionString = "cannotexecute";
            db.KeepConnection   = true;
            db.DBProvider       = typeof(MockDbConnection).AssemblyQualifiedName;
            db.Initialize(null);
            db.WriteAsyncLogEvents(
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            db.Close();

            Assert.AreEqual(3, exceptions.Count);
            Assert.IsNotNull(exceptions[0]);
            Assert.IsNotNull(exceptions[1]);
            Assert.IsNotNull(exceptions[2]);
            Assert.AreEqual("Failure during ExecuteNonQuery", exceptions[0].Message);
            Assert.AreEqual("Failure during ExecuteNonQuery", exceptions[1].Message);
            Assert.AreEqual("Failure during ExecuteNonQuery", exceptions[2].Message);

            string expectedLog = @"Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
";

            AssertLog(expectedLog);
        }
        public void AsyncTargetWrapperCloseTest()
        {
            var myTarget = new MyAsyncTarget
            {
                ThrowExceptions = true
            };

            var targetWrapper = new AsyncTargetWrapper(myTarget)
            {
                OverflowAction            = AsyncTargetWrapperOverflowAction.Grow,
                TimeToSleepBetweenBatches = 1000,
                Name = "AsyncTargetWrapperCloseTest_Wrapper",
            };

            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));

            // quickly close the target before the timer elapses
            targetWrapper.Close();
        }
        public void AsyncRequestQueueWithGrowBehaviorTest()
        {
            var ev1 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
            var ev2 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
            var ev3 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
            var ev4 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });

            var queue = new AsyncRequestQueue(new NLog.Config.LoggingConfiguration(), 3, AsyncTargetWrapperOverflowAction.Grow);

            Assert.Equal(3, queue.RequestLimit);
            Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, queue.OnOverflow);
            Assert.Equal(0, queue.RequestCount);
            queue.Enqueue(ev1);
            Assert.Equal(1, queue.RequestCount);
            queue.Enqueue(ev2);
            Assert.Equal(2, queue.RequestCount);
            queue.Enqueue(ev3);
            Assert.Equal(3, queue.RequestCount);
            queue.Enqueue(ev4);
            Assert.Equal(4, queue.RequestCount);
            int actualCount;

            AsyncLogEventInfo[] logEventInfos = queue.DequeueBatch(10, out actualCount);


            Assert.Equal(4, actualCount);
            Assert.Equal(0, queue.RequestCount);

            // ev1 is lost
            Assert.Same(logEventInfos[0].LogEvent, ev1.LogEvent);
            Assert.Same(logEventInfos[1].LogEvent, ev2.LogEvent);
            Assert.Same(logEventInfos[2].LogEvent, ev3.LogEvent);
            Assert.Same(logEventInfos[3].LogEvent, ev4.LogEvent);
            Assert.Same(logEventInfos[0].Continuation, ev1.Continuation);
            Assert.Same(logEventInfos[1].Continuation, ev2.Continuation);
            Assert.Same(logEventInfos[2].Continuation, ev3.Continuation);
            Assert.Same(logEventInfos[3].Continuation, ev4.Continuation);
        }
        /// <summary>
        /// Initializes the target. Can be used by inheriting classes
        /// to initialize logging.
        /// </summary>
        protected override void InitializeTarget()
        {
            base.InitializeTarget();

            _machineName = GetMachineName();

            string connectionString = string.Empty;
            string serviceUri       = string.Empty;
            string tenantIdentity   = string.Empty;
            string resourceIdentity = string.Empty;
            string clientIdentity   = string.Empty;
            string accountName      = string.Empty;
            string accessKey        = string.Empty;

            var defaultLogEvent = LogEventInfo.CreateNullEvent();

            try
            {
                connectionString = ConnectionString?.Render(defaultLogEvent);
                if (string.IsNullOrEmpty(connectionString))
                {
                    serviceUri       = ServiceUri?.Render(defaultLogEvent);
                    tenantIdentity   = TenantIdentity?.Render(defaultLogEvent);
                    resourceIdentity = ResourceIdentity?.Render(defaultLogEvent);
                    clientIdentity   = ClientIdentity?.Render(defaultLogEvent);
                    accountName      = AccountName?.Render(defaultLogEvent);
                    accessKey        = AccessKey?.Render(defaultLogEvent);
                }

                _cloudTableService.Connect(connectionString, serviceUri, tenantIdentity, resourceIdentity, clientIdentity, accountName, accessKey);
                InternalLogger.Trace("AzureDataTablesTarget(Name={0}): Initialized", Name);
            }
            catch (Exception ex)
            {
                InternalLogger.Error(ex, "AzureDataTablesTarget(Name={0}): Failed to create TableClient with connectionString={1}.", Name, connectionString);
                throw;
            }
        }
Beispiel #12
0
        public void WindowsIdentityTest()
        {
#if NETSTANDARD
            if (IsTravis())
            {
                return; // NetCore on Travis not supporting WindowsIdentity
            }
#endif

            var userDomainName = Environment.GetEnvironmentVariable("USERDOMAIN") ?? string.Empty;
            var userName       = Environment.GetEnvironmentVariable("USERNAME") ?? string.Empty;
            if (!string.IsNullOrEmpty(userDomainName))
            {
                userName = userDomainName + "\\" + userName;
            }

            NLog.Layouts.Layout layout = "${windows-identity}";
            var result = layout.Render(LogEventInfo.CreateNullEvent());
            if (!string.IsNullOrEmpty(result) || !IsAppVeyor())
            {
                Assert.Equal(userName, result);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Initialize the target based on the options set
        /// </summary>
        /// <remarks>
        /// This is part of the NLog is called when the Configurations of the LogManager are set.
        /// If any of the configuration properties are modified then you must set anew the Configuration of the LogManager.
        /// </remarks>
        protected override void InitializeTarget()
        {
            if (this.UseConsoleLog)
            {
                this.ActivateConsoleLog();
            }

            if (this.LogLog.IsDebugEnabled)
            {
                this.LogLog.Debug("Activating options");
            }

            // Initialize the sender
            if (this.SumoLogicMessageSender == null)
            {
                this.SumoLogicMessageSender = new SumoLogicMessageSender(this.HttpMessageHandler, this.LogLog, "sumo-nlog-sender");
            }

            var url = _urlLayout?.Render(LogEventInfo.CreateNullEvent()) ?? string.Empty;

            this.SumoLogicMessageSender.ConnectionTimeout = TimeSpan.FromMilliseconds(this.ConnectionTimeout);
            this.SumoLogicMessageSender.Url = string.IsNullOrEmpty(url) ? null : new Uri(url);
        }
        public void LocalIpAddress_Multiple_TakesFirstIpv6IfRequested()
        {
            // Arrange
            var ipv6 = "fe80::200:f8ff:fe21:67cf";

            var networkInterfaceRetrieverMock = new NetworkInterfaceRetrieverBuilder()
                                                .WithInterface(NetworkInterfaceType.Ethernet, "F0-E0-D2-C3-B4-A5")
                                                .WithIp("1.0.10.11")
                                                .WithInterface(NetworkInterfaceType.Ethernet, Mac1)
                                                .WithIp(ipv6)
                                                .Build();

            var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock)
            {
                AddressFamily = AddressFamily.InterNetworkV6
            };

            // Act
            var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent());

            // Assert
            Assert.Equal(ipv6, result);
        }
Beispiel #15
0
        public static bool TryGetLogfileContent(string loggerName, out string result)
        {
            LogManager.Flush();
            var fileTarget = LogManager.Configuration.ConfiguredNamedTargets.FirstOrDefault(t =>
                                                                                            t.GetType().IsAssignableFrom(typeof(FileTarget)) && t.Name == loggerName) as FileTarget;

            if (fileTarget == null)
            {
                result = $"Logger '{loggerName}' not found.";
                return(false);
            }

            var fileName = fileTarget.FileName.Render(LogEventInfo.CreateNullEvent());

            if (!File.Exists(fileName))
            {
                result = $"File '{fileName}' not found.";
                return(false);
            }

            result = File.ReadAllText(fileName);
            return(true);
        }
Beispiel #16
0
        public void LayoutInitTest2()
        {
            var lr = new MockLayout();
            Assert.Equal(0, lr.InitCount);
            Assert.Equal(0, lr.CloseCount);

            // calls to Close() will be ignored because 
            lr.Close();
            Assert.Equal(0, lr.InitCount);
            Assert.Equal(0, lr.CloseCount);

            lr.Initialize(null);
            Assert.Equal(1, lr.InitCount);

            // make sure render will not call another Init
            lr.Render(LogEventInfo.CreateNullEvent());
            Assert.Equal(1, lr.InitCount);
            Assert.Equal(0, lr.CloseCount);

            lr.Close();
            Assert.Equal(1, lr.InitCount);
            Assert.Equal(1, lr.CloseCount);
        }
Beispiel #17
0
        private GoogleCredential GetCredentialFromConfiguration()
        {
            var nullLogEvent   = LogEventInfo.CreateNullEvent();
            var credentialFile = CredentialFile?.Render(nullLogEvent);
            var credentialJson = CredentialJson?.Render(nullLogEvent);

            GaxPreconditions.CheckState(string.IsNullOrWhiteSpace(credentialFile) || string.IsNullOrWhiteSpace(credentialJson),
                                        $"{nameof(CredentialFile)} and {nameof(CredentialJson)} must not both be set.");
            var credential =
                !string.IsNullOrWhiteSpace(credentialFile) ? GoogleCredential.FromFile(credentialFile) :
                !string.IsNullOrWhiteSpace(credentialJson) ? GoogleCredential.FromJson(credentialJson) :
                null;

            if (credential == null)
            {
                return(null);
            }
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(s_oAuthScopes);
            }
            return(credential);
        }
Beispiel #18
0
        private void ActivateLogIdAndResource(string logId)
        {
            string            projectId = null;
            MonitoredResource resource  = null;

            if (!DisableResourceTypeDetection)
            {
                resource = MonitoredResourceBuilder.FromPlatform(_platform);
                resource.Labels.TryGetValue("project_id", out projectId);
            }

            if (projectId == null)
            {
                // Either platform detection is disabled, or it detected an unknown platform.
                // So use the manually configured projectId and override the resource.
                projectId = GaxPreconditions.CheckNotNull(ProjectId?.Render(LogEventInfo.CreateNullEvent()), nameof(ProjectId));
                if (ResourceType == null)
                {
                    resource = new MonitoredResource {
                        Type = "global", Labels = { { "project_id", projectId } }
                    };
                }
                else
                {
                    resource = new MonitoredResource {
                        Type   = ResourceType,
                        Labels = { ResourceLabels.ToDictionary(x => x.Name, x => x.Layout.Render(LogEventInfo.CreateNullEvent())) }
                    };
                }
            }

            _resource = resource;
            var logName = new LogName(projectId, logId);

            _logName        = logName.ToString();
            _logNameToWrite = LogNameOneof.From(logName);
        }
Beispiel #19
0
        public void AsyncRequestQueueWithGrowBehaviorTest()
        {
            var ev1 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
            var ev2 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
            var ev3 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
            var ev4 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });

            var queue = new AsyncRequestQueue(3, AsyncTargetWrapperOverflowAction.Grow);

            Assert.AreEqual(3, queue.RequestLimit);
            Assert.AreEqual(AsyncTargetWrapperOverflowAction.Grow, queue.OnOverflow);
            Assert.AreEqual(0, queue.RequestCount);
            queue.Enqueue(ev1);
            Assert.AreEqual(1, queue.RequestCount);
            queue.Enqueue(ev2);
            Assert.AreEqual(2, queue.RequestCount);
            queue.Enqueue(ev3);
            Assert.AreEqual(3, queue.RequestCount);
            queue.Enqueue(ev4);
            Assert.AreEqual(4, queue.RequestCount);

            AsyncLogEventInfo[] logEventInfos = queue.DequeueBatch(10);
            int result = logEventInfos.Length;

            Assert.AreEqual(4, result);
            Assert.AreEqual(0, queue.RequestCount);

            // ev1 is lost
            Assert.AreSame(logEventInfos[0].LogEvent, ev1.LogEvent);
            Assert.AreSame(logEventInfos[1].LogEvent, ev2.LogEvent);
            Assert.AreSame(logEventInfos[2].LogEvent, ev3.LogEvent);
            Assert.AreSame(logEventInfos[3].LogEvent, ev4.LogEvent);
            Assert.AreSame(logEventInfos[0].Continuation, ev1.Continuation);
            Assert.AreSame(logEventInfos[1].Continuation, ev2.Continuation);
            Assert.AreSame(logEventInfos[2].Continuation, ev3.Continuation);
            Assert.AreSame(logEventInfos[3].Continuation, ev4.Continuation);
        }
Beispiel #20
0
        public void InitializeFailedTest()
        {
            var target = new MyTarget();

            target.ThrowOnInitialize = true;
            try
            {
                target.Initialize(null);
                Assert.Fail("Expected exception.");
            }
            catch (InvalidOperationException)
            {
            }

            // after exception in Initialize(), the target becomes non-functional and all Write() operations
            var exceptions = new List <Exception>();

            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.AreEqual(0, target.WriteCount);
            Assert.AreEqual(1, exceptions.Count);
            Assert.IsNotNull(exceptions[0]);
            Assert.AreEqual("Target " + target + " failed to initialize.", exceptions[0].Message);
            Assert.AreEqual("Init error.", exceptions[0].InnerException.Message);
        }
Beispiel #21
0
        /// <summary>
        /// Initializes the target.
        /// </summary>
        protected override void InitializeTarget()
        {
            _pauseLogging = false;
            if (DetectConsoleAvailable)
            {
                string reason;
                _pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason);
                if (_pauseLogging)
                {
                    InternalLogger.Info("Console has been detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {0}", reason);
                }
            }
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
            if (_encoding != null && !_pauseLogging)
            {
                Console.OutputEncoding = _encoding;
            }
#endif
            base.InitializeTarget();
            if (Header != null)
            {
                this.WriteToOutput(Header.Render(LogEventInfo.CreateNullEvent()));
            }
        }
Beispiel #22
0
        public void TestResetVariablesOnReload()
        {
            string config = @"<nlog autoReload='true' keepVariablesOnReload='false'>
                                <variable name='var1' value='' />
                                <variable name='var2' value='keep_value' />
                            </nlog>";

            var configLoader  = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment);
            var logFactory    = new LogFactory(configLoader);
            var configuration = XmlLoggingConfigurationMock.CreateFromXml(logFactory, config);

            logFactory.Configuration = configuration;
            logFactory.Configuration.Variables["var1"] = "new_value";
            logFactory.Configuration.Variables["var3"] = "new_value3";
            configLoader.ReloadConfigOnTimer(configuration);
            LogEventInfo nullEvent = LogEventInfo.CreateNullEvent();

            Assert.Equal("", logFactory.Configuration.Variables["var1"].Render(nullEvent));
            Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent));

            logFactory.Configuration = configuration.Reload();
            Assert.Equal("", logFactory.Configuration.Variables["var1"].Render(nullEvent));
            Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent));
        }
        /// <inheritdoc/>
        protected override void InitializeTarget()
        {
            var providerName = (ProviderName?.Render(LogEventInfo.CreateNullEvent()) ?? string.Empty).Trim();

            if (string.IsNullOrEmpty(providerName))
            {
                throw new NLogConfigurationException("EtwEventSourceTarget - ProviderName must be configured");
            }

            if (!EventSources.TryGetValue(providerName, out _eventSource))
            {
                _eventSource = new EventSource(providerName, EventSourceSettings.EtwSelfDescribingEventFormat);
                if (_eventSource.ConstructionException != null)
                {
                    NLog.Common.InternalLogger.Error("EtwEventSourceTarget(Name={0}): EventSource({1}) constructor threw exception: {2}", Name, providerName, _eventSource.ConstructionException);
                }
                if (!EventSources.TryAdd(providerName, _eventSource))
                {
                    _eventSource = EventSources[providerName];
                }
            }

            base.InitializeTarget();
        }
        public void ImpersonatingWrapperTest()
        {
            var wrapped = new MyTarget()
            {
                ExpectedUser = Environment.MachineName + "\\" + NLogTestUser,
            };

            var wrapper = new ImpersonatingTargetWrapper()
            {
                UserName      = NLogTestUser,
                Password      = NLogTestUserPassword,
                Domain        = Environment.MachineName,
                WrappedTarget = wrapped,
            };

            // wrapped.Initialize(null);
            wrapper.Initialize(null);

            var exceptions = new List <Exception>();

            wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.Equal(1, exceptions.Count);
            wrapper.WriteAsyncLogEvents(
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.Equal(4, exceptions.Count);
            wrapper.Flush(exceptions.Add);
            Assert.Equal(5, exceptions.Count);
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            wrapper.Close();
        }
Beispiel #25
0
        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 => { }));
                targetWrapper.Close();
            },
                LogLevel.Trace);

            Assert.True(internalLog.StartsWith("Error Error in lazy writer timer procedure: System.NullReferenceException", StringComparison.Ordinal), internalLog);
        }
        public void RevertToSameIdentity()
        {
            var wrapped = new MyTarget()
            {
                ExpectedUser = LocalMachineName + "\\" + Environment.UserName,
            };

            var wrapper = new ImpersonatingTargetWrapper()
            {
                WrappedTarget = wrapped,
                RevertToSelf  = true,
            };

            var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
            {
                cfg.Configuration.AddRuleForAllLevels(wrapper);
            }).LogFactory;

            var exceptions = new List <Exception>();

            wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.Single(exceptions);
            wrapper.WriteAsyncLogEvents(
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.Equal(4, exceptions.Count);
            wrapper.Flush(exceptions.Add);
            Assert.Equal(5, exceptions.Count);
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            logFactory.Shutdown();
        }
Beispiel #27
0
        public void AsyncRequestQueueEventDiscardedEventTest()
        {
            var ev1 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
            var ev2 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
            var ev3 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
            var ev4 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });

            var queue  = new AsyncRequestQueue(3, AsyncTargetWrapperOverflowAction.Discard);
            var raised = false;
            var eh     = new BufferOverflowEventHandler(
                (a, b, c, d) =>
            {
                Assert.Same(a, AsyncTargetWrapperOverflowAction.Discard);
                Assert.Same(ev1, d);
                raised = true;
            });

            queue.Enqueue(ev1);
            queue.Enqueue(ev2);
            queue.Enqueue(ev3);
            Assert.False(raised);
            queue.Enqueue(ev4);
            Assert.True(raised);
        }
Beispiel #28
0
        public void RegisterLayoutRendererTest()
        {
            var httpcontextMock = SetupHttpAccessorWithHttpContext();

#if ASP_NET_CORE
            httpcontextMock.Connection.LocalPort.Returns(123);
#else
            httpcontextMock.Request.RawUrl.Returns("123");
#endif

            // Act
            AspNetLayoutRendererBase.Register("test-web",
                                              (logEventInfo, httpContext, loggingConfiguration) =>
#if ASP_NET_CORE
                                              httpContext.Connection.LocalPort);
#else
                                              httpContext.Request.RawUrl);
#endif
            Layout l       = "${test-web}";
            var    restult = l.Render(LogEventInfo.CreateNullEvent());

            // Assert
            Assert.Equal("123", restult);
        }
        public void TestAllPropertiesWhenActivityNull()
        {
            bool orgThrowExceptions = LogManager.ThrowExceptions;

            try
            {
                LogManager.ThrowExceptions          = true;
                System.Diagnostics.Activity.Current = null;

                var logEvent = LogEventInfo.CreateNullEvent();

                foreach (ActivityTraceProperty property in Enum.GetValues(typeof(ActivityTraceProperty)))
                {
                    ActivityTraceLayoutRenderer layoutRenderer = new ActivityTraceLayoutRenderer();
                    layoutRenderer.Property = property;
                    var result = layoutRenderer.Render(logEvent);
                    Assert.True(string.IsNullOrEmpty(result));
                }
            }
            finally
            {
                LogManager.ThrowExceptions = orgThrowExceptions;
            }
        }
        public void AsyncRequestQueueWithBlockBehavior()
        {
            var queue = new AsyncRequestQueue(10, AsyncTargetWrapperOverflowAction.Block);

            ManualResetEvent producerFinished = new ManualResetEvent(false);

            int pushingEvent = 0;

            ThreadPool.QueueUserWorkItem(
                s =>
            {
                // producer thread
                for (int i = 0; i < 1000; ++i)
                {
                    AsyncLogEventInfo logEvent = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
                    logEvent.LogEvent.Message  = "msg" + i;

                    // Console.WriteLine("Pushing event {0}", i);
                    pushingEvent = i;
                    queue.Enqueue(logEvent);
                }

                producerFinished.Set();
            });

            // consumer thread
            AsyncLogEventInfo[] logEventInfos;
            int total = 0;

            while (total < 500)
            {
                int left = 500 - total;

                logEventInfos = queue.DequeueBatch(left);
                int got = logEventInfos.Length;
                Assert.True(got <= queue.RequestLimit);
                total += got;
            }

            Thread.Sleep(500);

            // producer is blocked on trying to push event #510
            Assert.Equal(510, pushingEvent);
            queue.DequeueBatch(1);
            total++;
            Thread.Sleep(500);

            // producer is now blocked on trying to push event #511

            Assert.Equal(511, pushingEvent);
            while (total < 1000)
            {
                int left = 1000 - total;

                logEventInfos = queue.DequeueBatch(left);
                int got = logEventInfos.Length;
                Assert.True(got <= queue.RequestLimit);
                total += got;
            }

            // producer should now finish
            producerFinished.WaitOne();
        }