public void WriteToStringWriterWithArgsTests()
        {
            try
            {
                // Expected result is the same for both types of method invocation.
                const string expected = "Warn WWW 0\nError EEE 0, 1\nFatal FFF 0, 1, 2\nTrace TTT 0, 1, 2\nDebug DDD 0, 1\nInfo III 0\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 {0}", 0);
                    InternalLogger.Error("EEE {0}, {1}", 0, 1);
                    InternalLogger.Fatal("FFF {0}, {1}, {2}", 0, 1, 2);
                    InternalLogger.Trace("TTT {0}, {1}, {2}", 0, 1, 2);
                    InternalLogger.Debug("DDD {0}, {1}", 0, 1);
                    InternalLogger.Info("III {0}", 0);

                    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 {0}", 0);
                    InternalLogger.Log(LogLevel.Error, "EEE {0}, {1}", 0, 1);
                    InternalLogger.Log(LogLevel.Fatal, "FFF {0}, {1}, {2}", 0, 1, 2);
                    InternalLogger.Log(LogLevel.Trace, "TTT {0}, {1}, {2}", 0, 1, 2);
                    InternalLogger.Log(LogLevel.Debug, "DDD {0}, {1}", 0, 1);
                    InternalLogger.Log(LogLevel.Info, "III {0}", 0);
                    TestWriter(expected, writer2);
                }
            }
            finally
            {
                InternalLogger.Reset();
            }
        }
Esempio n. 2
0
            public void Dispose()
            {
                if (File.Exists(InternalLogger.LogFile))
                {
                    File.Delete(InternalLogger.LogFile);
                }

                InternalLogger.Reset();

                //restore logmanager
                LogManager.GlobalThreshold       = this.globalThreshold;
                LogManager.ThrowExceptions       = this.throwExceptions;
                LogManager.ThrowConfigExceptions = this.throwConfigExceptions;
            }
Esempio n. 3
0
        protected NLogTestBase()
        {
            //reset before every test
            LogManager.Configuration = null;    // Will close any existing config
            LogManager.LogFactory.ResetCandidateConfigFilePath();

            InternalLogger.Reset();
            InternalLogger.LogLevel          = LogLevel.Off;
            LogManager.ThrowExceptions       = true; // Ensure exceptions are thrown by default during unit-testing
            LogManager.ThrowConfigExceptions = null;
            System.Diagnostics.Trace.Listeners.Clear();
#if !NETSTANDARD
            System.Diagnostics.Debug.Listeners.Clear();
#endif
        }
Esempio n. 4
0
        public void LoadExtensionFromAppDomain()
        {
            try
            {
                // ...\NLog\tests\NLog.UnitTests\bin\Debug\netcoreapp2.0\nlog.dll
                var nlogDirectory              = new DirectoryInfo(ConfigurationItemFactory.GetAutoLoadingFileLocations().First().Key);
                var configurationDirectory     = nlogDirectory.Parent;
                var testsDirectory             = configurationDirectory.Parent.Parent.Parent;
                var manuallyLoadedAssemblyPath = Path.Combine(testsDirectory.FullName, "ManuallyLoadedExtension", "bin", configurationDirectory.Name,
#if NETSTANDARD
                                                              "netstandard2.0",
#else
                                                              nlogDirectory.Name,
#endif
                                                              "ManuallyLoadedExtension.dll");
                Assembly.LoadFrom(manuallyLoadedAssemblyPath);

                InternalLogger.LogLevel = LogLevel.Trace;
                var writer = new StringWriter();
                InternalLogger.LogWriter = writer;

                var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
    <extensions>
        <add assembly='ManuallyLoadedExtension' />
    </extensions>

    <targets>
        <target name='t' type='ManuallyLoadedTarget' />
    </targets>
</nlog>");

                // We get Exception for normal Assembly-Load only in net452.
#if !NETSTANDARD && !MONO
                var logs = writer.ToString();
                Assert.Contains("Try find 'ManuallyLoadedExtension' in current domain", logs);
#endif

                // Was AssemblyLoad successful?
                var autoLoadedTarget = configuration.FindTargetByName("t");
                Assert.Equal("ManuallyLoadedExtension.ManuallyLoadedTarget", autoLoadedTarget.GetType().FullName);
            }
            finally
            {
                InternalLogger.Reset();
            }
        }
Esempio n. 5
0
        public void CreateFileInCurrentDirectoryTests()
        {
            string expected =
                "Warn WWW" + Environment.NewLine +
                "Error EEE" + Environment.NewLine +
                "Fatal FFF" + Environment.NewLine +
                "Trace TTT" + Environment.NewLine +
                "Debug DDD" + Environment.NewLine +
                "Info III" + Environment.NewLine;

            // Store off the previous log file
            string previousLogFile = InternalLogger.LogFile;

            var tempFileName = Path.GetRandomFileName();

            try
            {
                InternalLogger.LogLevel         = LogLevel.Trace;
                InternalLogger.IncludeTimestamp = false;

                Assert.False(File.Exists(tempFileName));

                // Set the log file, which only has a filename
                InternalLogger.LogFile = tempFileName;

                Assert.False(File.Exists(tempFileName));

                // 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");

                AssertFileContents(tempFileName, expected, Encoding.UTF8);
                Assert.True(File.Exists(tempFileName));
            }
            finally
            {
                InternalLogger.Reset();
                if (File.Exists(tempFileName))
                {
                    File.Delete(tempFileName);
                }
            }
        }
Esempio n. 6
0
        public void CreateDirectoriesIfNeededTests(string rawLogLevel, bool shouldCreateDirectory)
        {
            var    tempPath           = Path.GetTempPath();
            var    tempFileName       = Path.GetRandomFileName();
            var    randomSubDirectory = Path.Combine(tempPath, Path.GetRandomFileName());
            string tempFile           = Path.Combine(randomSubDirectory, tempFileName);

            try
            {
                InternalLogger.LogLevel         = LogLevel.FromString(rawLogLevel);
                InternalLogger.IncludeTimestamp = false;

                if (Directory.Exists(randomSubDirectory))
                {
                    Directory.Delete(randomSubDirectory);
                }
                Assert.False(Directory.Exists(randomSubDirectory));

                // Set the log file, which will only create the needed directories
                InternalLogger.LogFile = tempFile;

                Assert.Equal(Directory.Exists(randomSubDirectory), shouldCreateDirectory);

                Assert.False(File.Exists(tempFile));

                InternalLogger.Log(LogLevel.FromString(rawLogLevel), "File and Directory created.");

                Assert.Equal(File.Exists(tempFile), shouldCreateDirectory);
            }
            finally
            {
                InternalLogger.Reset();

                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }

                if (Directory.Exists(randomSubDirectory))
                {
                    Directory.Delete(randomSubDirectory);
                }
            }
        }
Esempio n. 7
0
        public void SetupInternalLoggerLogToWriterTest()
        {
            try
            {
                // Arrange
                InternalLogger.Reset();
                var logFactory = new LogFactory();

                // Act
                logFactory.Setup().SetupInternalLogger(b => b.SetMinimumLogLevel(LogLevel.Fatal).LogToWriter(Console.Out));

                // Assert
                Assert.Equal(Console.Out, InternalLogger.LogWriter);
            }
            finally
            {
                InternalLogger.Reset();
            }
        }
Esempio n. 8
0
        protected NLogTestBase()
        {
            //reset before every test
            if (LogManager.Configuration != null)
            {
                //flush all events if needed.
                LogManager.Configuration.Close();
            }

            if (LogManager.LogFactory != null)
            {
                LogManager.LogFactory.ResetCandidateConfigFilePath();
            }

            LogManager.Configuration = null;
            InternalLogger.Reset();
            LogManager.ThrowExceptions       = false;
            LogManager.ThrowConfigExceptions = null;
        }
Esempio n. 9
0
        public void SetupInternalLoggerLogToTraceTest()
        {
            try
            {
                // Arrange
                InternalLogger.Reset();
                var logFactory = new LogFactory();

                // Act
                logFactory.Setup().SetupInternalLogger(b => b.SetMinimumLogLevel(LogLevel.Fatal).LogToTrace(true));

                // Assert
                Assert.True(InternalLogger.LogToTrace);
            }
            finally
            {
                InternalLogger.Reset();
            }
        }
Esempio n. 10
0
        public void SetupInternalLoggerSetLogLevelTest(string logLevelName)
        {
            try
            {
                // Arrange
                var logLevel = LogLevel.FromString(logLevelName);
                InternalLogger.Reset();
                var logFactory = new LogFactory();

                // Act
                logFactory.Setup().SetupInternalLogger(b => b.SetMinimumLogLevel(logLevel));

                // Assert
                Assert.Equal(logLevel, InternalLogger.LogLevel);
            }
            finally
            {
                InternalLogger.Reset();
            }
        }
Esempio n. 11
0
        public void SetupInternalLoggerLogToFileTest()
        {
            try
            {
                // Arrange
                var logFile = $"{nameof(SetupInternalLoggerLogToFileTest)}.txt";
                InternalLogger.Reset();
                var logFactory = new LogFactory();

                // Act
                logFactory.Setup().SetupInternalLogger(b => b.SetMinimumLogLevel(LogLevel.Fatal).LogToFile(logFile));

                // Assert
                Assert.Equal(logFile, InternalLogger.LogFile);
            }
            finally
            {
                InternalLogger.Reset();
            }
        }
Esempio n. 12
0
        public void SetupInternalLoggerSetupFromEnvironmentVariablesTest()
        {
            try
            {
                // Arrange
                InternalLogger.Reset();
                var logFactory = new LogFactory();
                InternalLogger.LogToConsole = true;

                // Act
                logFactory.Setup().SetupInternalLogger(b => b.SetupFromEnvironmentVariables().SetMinimumLogLevel(LogLevel.Fatal));

                // Assert
                Assert.False(InternalLogger.LogToConsole);
                Assert.Equal(LogLevel.Fatal, InternalLogger.LogLevel);
            }
            finally
            {
                InternalLogger.Reset();
            }
        }
Esempio n. 13
0
            public void Dispose()
            {
                InternalLogger.Reset();

                if (ConsoleOutputWriter != null)
                {
                    Console.SetOut(oldConsoleOutputWriter);
                }
                if (ConsoleErrorWriter != null)
                {
                    Console.SetError(oldConsoleErrorWriter);
                }

                if (File.Exists(InternalLogger.LogFile))
                {
                    File.Delete(InternalLogger.LogFile);
                }

                //restore logmanager
                LogManager.GlobalThreshold       = globalThreshold;
                LogManager.ThrowExceptions       = throwExceptions;
                LogManager.ThrowConfigExceptions = throwConfigExceptions;
            }
Esempio n. 14
0
        protected NLogTestBase()
        {
            //reset before every test
            if (LogManager.Configuration != null)
            {
                //flush all events if needed.
                LogManager.Configuration.Close();
            }

            if (LogManager.LogFactory != null)
            {
                LogManager.LogFactory.ResetCandidateConfigFilePath();
            }

            LogManager.Configuration = null;
            InternalLogger.Reset();
            LogManager.ThrowExceptions       = false;
            LogManager.ThrowConfigExceptions = null;
            System.Diagnostics.Trace.Listeners.Clear();
#if !NETSTANDARD
            System.Diagnostics.Debug.Listeners.Clear();
#endif
        }
Esempio n. 15
0
        protected NLogTestBase()
        {
#if MONO
            if (PlatformDetector.IsUnix)
            {
                // Force filesystem to flush to disk
                Syscall.sync();
            }
#endif
            //reset before every test
            if (LogManager.Configuration != null)
            {
                //flush all events if needed.
                LogManager.Configuration.Close();
            }
            LogManager.Configuration = null;
            InternalLogger.Reset();
            LogManager.ThrowExceptions = false;
            Trace.Listeners.Clear();
#if !SILVERLIGHT
            Debug.Listeners.Clear();
#endif
        }
Esempio n. 16
0
        public void WriteToFileTests()
        {
            string expected =
                "Warn WWW" + Environment.NewLine +
                "Error EEE" + Environment.NewLine +
                "Fatal FFF" + Environment.NewLine +
                "Trace TTT" + Environment.NewLine +
                "Debug DDD" + Environment.NewLine +
                "Info III" + Environment.NewLine;

            var tempFile = Path.GetTempFileName();

            try
            {
                InternalLogger.LogLevel         = LogLevel.Trace;
                InternalLogger.IncludeTimestamp = false;
                InternalLogger.LogFile          = tempFile;

                // 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");

                AssertFileContents(tempFile, expected, Encoding.UTF8);
            }
            finally
            {
                InternalLogger.Reset();
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
Esempio n. 17
0
        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;
            }
        }
Esempio n. 18
0
        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();
            }
        }
Esempio n. 19
0
 public void Dispose()
 {
     TimeSource.Current = new FastLocalTimeSource();
     InternalLogger.Reset();
 }
Esempio n. 20
0
 /// <summary>
 /// Configure the InternalLogger properties from Environment-variables and App.config using <see cref="InternalLogger.Reset"/>
 /// </summary>
 /// <remarks>
 /// Recognizes the following environment-variables:
 ///
 /// - NLOG_INTERNAL_LOG_LEVEL
 /// - NLOG_INTERNAL_LOG_FILE
 /// - NLOG_INTERNAL_LOG_TO_CONSOLE
 /// - NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR
 /// - NLOG_INTERNAL_LOG_TO_TRACE
 /// - NLOG_INTERNAL_INCLUDE_TIMESTAMP
 ///
 /// Legacy .NetFramework platform will also recognizes the following app.config settings:
 ///
 /// - nlog.internalLogLevel
 /// - nlog.internalLogFile
 /// - nlog.internalLogToConsole
 /// - nlog.internalLogToConsoleError
 /// - nlog.internalLogToTrace
 /// - nlog.internalLogIncludeTimestamp
 /// </remarks>
 public static ISetupInternalLoggerBuilder SetupFromEnvironmentVariables(this ISetupInternalLoggerBuilder setupBuilder)
 {
     InternalLogger.Reset();
     return(setupBuilder);
 }