/// <summary> /// Initializes a new instance of the <see cref="Logger"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="level">The log level.</param> /// <param name="writer">The writer where logs are sent.</param> public Logger(string name, InternalTraceLevel level, TextWriter writer) { this.maxLevel = level; this.writer = writer; this.fullname = this.name = name; int index = fullname.LastIndexOf('.'); if (index >= 0) this.name = fullname.Substring(index + 1); }
public static void ReInitialize(string logName, InternalTraceLevel level) { if (initialized) { Close(); initialized = false; } Initialize(logName, level); }
//public static void Initialize(string logName) //{ // int lev = (int) new System.Diagnostics.TraceSwitch("NTrace", "NUnit internal trace").Level; // Initialize(logName, (InternalTraceLevel)lev); //} public static void Initialize(string logName, InternalTraceLevel level) { if (!initialized) { LogName = logName; Level = level; initialized = true; } }
/// <summary> /// Initializes a new instance of the <see cref="Logger"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="level">The log level.</param> /// <param name="writer">The writer where logs are sent.</param> public Logger(string name, InternalTraceLevel level, TextWriter writer) { this.maxLevel = level; this.writer = writer; this.fullname = this.name = name; int index = fullname.LastIndexOf('.'); if (index >= 0) { this.name = fullname.Substring(index + 1); } }
private void InitializeInternalTrace(string assemblyPath, InternalTraceLevel traceLevel) { if (traceLevel != InternalTraceLevel.Off) { #if !SILVERLIGHT var logName = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath)); #else var logName = string.Format(LOG_FILE_FORMAT, DateTime.Now.ToString("o"), Path.GetFileName(assemblyPath)); #endif InternalTrace.Initialize(Path.Combine(Environment.CurrentDirectory, logName), traceLevel); } }
private void WriteLog(InternalTraceLevel level, string message) { writer.WriteLine(TRACE_FMT, DateTime.Now.ToString(TIME_FMT), level == InternalTraceLevel.Verbose ? "Debug" : level.ToString(), #if NET20 System.Threading.Thread.CurrentThread.ManagedThreadId, #else Environment.CurrentManagedThreadId, #endif name, message); }
private void WriteLog(InternalTraceLevel level, string message) { _writer.WriteLine(TraceFmt, DateTime.Now.ToString(TimeFmt), level, #if NET20 System.Threading.Thread.CurrentThread.ManagedThreadId, #else Environment.CurrentManagedThreadId, #endif _name, message); }
public static void Log(InternalTraceLevel level, string message, string category, Exception ex) { Writer.WriteLine("{0} {1,-5} [{2,2}] {3}: {4}", DateTime.Now.ToString(TIME_FMT), level == InternalTraceLevel.Verbose ? "Debug" : level.ToString(), System.Threading.Thread.CurrentThread.ManagedThreadId, category, message); if (ex != null) { Writer.WriteLine(ex.ToString()); } }
/// <summary> /// Initialize the internal trace using a provided TextWriter and level /// </summary> /// <param name="writer">A TextWriter</param> /// <param name="level">The InternalTraceLevel</param> public static void Initialize(TextWriter writer, InternalTraceLevel level) { if (!Initialized) { traceLevel = level; if (traceWriter == null && traceLevel > InternalTraceLevel.Off) { traceWriter = new InternalTraceWriter(writer); traceWriter.WriteLine("InternalTrace: Initializing at level " + traceLevel.ToString()); } Initialized = true; } }
public static void Initialize(string logName, InternalTraceLevel level) { if (!initialized) { Level = level; if (writer == null && Level > InternalTraceLevel.Off) { writer = new InternalTraceWriter(logName); writer.WriteLine("InternalTrace: Initializing at level " + Level.ToString()); } initialized = true; } }
/// <summary> /// Initialize the internal trace facility using the name of the log /// to be written to and the trace level. /// </summary> /// <param name="logName">The log name</param> /// <param name="level">The trace level</param> public static void Initialize(string logName, InternalTraceLevel level) { if (!Initialized) { traceLevel = level; if (traceWriter == null && traceLevel > InternalTraceLevel.Off) { traceWriter = new InternalTraceWriter(logName); traceWriter.WriteLine("InternalTrace: Initializing at level {0}", traceLevel); } Initialized = true; } else traceWriter.WriteLine("InternalTrace: Ignoring attempted re-initialization at level {0}", level); }
public override void ApplySettings() { try { ConfigManager.OptionSection.Options["Options.InternalTraceLevel"].Value = traceLevelCombox.Text; ConfigManager.RefreshOptions(); ConfigManager.Save(); } catch (Exception ex) { throw new ApplicationException(Resources.SaveOptionsInternalTraceLevelFailure, ex); } InternalTraceLevel level = (InternalTraceLevel)Enum.Parse(InternalTraceLevel.Default.GetType(), traceLevelCombox.Text, true); InternalTrace.ReInitialize("CodeBuilder_%p.log", level); }
/// <summary> /// Initialize the internal trace facility using the name of the log /// to be written to and the trace level. /// </summary> /// <param name="logName">The log name</param> /// <param name="level">The trace level</param> public static void Initialize(string logName, InternalTraceLevel level) { if (!Initialized) { traceLevel = level; if (traceWriter == null && traceLevel > InternalTraceLevel.Off) { traceWriter = new InternalTraceWriter(logName); traceWriter.WriteLine("InternalTrace: Initializing at level {0}", traceLevel); } Initialized = true; } else { traceWriter.WriteLine("InternalTrace: Ignoring attempted re-initialization at level {0}", level); } }
public void InitializeDomain(int level) { InternalTraceLevel traceLevel = (InternalTraceLevel)level; InternalTrace.Initialize("%a_%p.log", traceLevel); log = InternalTrace.GetLogger(typeof(DomainInitializer)); AppDomain domain = AppDomain.CurrentDomain; log.Info("Initializing domain {0}", domain.FriendlyName); log.Debug(" Base Directory: {0}", domain.BaseDirectory); log.Debug(" Probing Path: {0}", domain.SetupInformation.PrivateBinPath); domain.DomainUnload += new EventHandler(OnDomainUnload); AssemblyResolver resolver = new AssemblyResolver(); resolver.AddDirectory(NUnitConfiguration.NUnitLibDirectory); resolver.AddDirectory(NUnitConfiguration.AddinDirectory); }
private void InitializeInternalTrace(string assemblyPath, InternalTraceLevel traceLevel) { if (traceLevel != InternalTraceLevel.Off) { #if !SILVERLIGHT var logName = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath)); #else var logName = string.Format(LOG_FILE_FORMAT, DateTime.Now.ToString("o"), Path.GetFileName(assemblyPath)); #endif #if NETCF // NETCF: Try to encapsulate this InternalTrace.Initialize(Path.Combine(NUnit.Env.DocumentFolder, logName), traceLevel); #else StreamWriter streamWriter = null; if (traceLevel > InternalTraceLevel.Off) { string logPath = Path.Combine(Environment.CurrentDirectory, logName); streamWriter = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write)); streamWriter.AutoFlush = true; } InternalTrace.Initialize(streamWriter, traceLevel); #endif } }
public void InitializeDomain(int level) { InternalTraceLevel traceLevel = (InternalTraceLevel)level; InternalTrace.Initialize("%a_%p.log", traceLevel); log = InternalTrace.GetLogger(typeof(DomainInitializer)); AppDomain domain = AppDomain.CurrentDomain; log.Info("Initializing domain {0}", domain.FriendlyName); log.Debug(" Base Directory: {0}", domain.BaseDirectory); log.Debug(" Probing Path: {0}", domain.SetupInformation.PrivateBinPath); domain.DomainUnload += new EventHandler(OnDomainUnload); AssemblyResolver resolver = new AssemblyResolver(); resolver.AddDirectory(NUnitConfiguration.NUnitLibDirectory); resolver.AddDirectory(NUnitConfiguration.AddinDirectory); // TODO: Temporary additions till we resolve a problem with pnunit // Test for existence is needed to avoid messing when the installation // does not include pnunit. string binDir = NUnitConfiguration.NUnitBinDirectory; string pnunitFrameworkPath = Path.Combine(binDir, "pnunit.framework.dll"); if (File.Exists(pnunitFrameworkPath)) { resolver.AddFile(pnunitFrameworkPath); } string pnunitAgentPath = Path.Combine(binDir, "pnunit-agent.exe"); if (File.Exists(pnunitAgentPath)) { resolver.AddFile(pnunitAgentPath); } }
public static void Log(InternalTraceLevel level, string message, string category) { Log(level, message, category, null); }
public static void ReInitialize(string logName, InternalTraceLevel level) { if (initialized){ Close(); initialized=false; } Initialize(logName, level); }
public static int Main(string[] args) { AgentId = new Guid(args[0]); AgencyUrl = args[1]; InternalTraceLevel traceLevel = InternalTraceLevel.Off; for (int i = 2; i < args.Length; i++) { string arg = args[i]; // NOTE: we can test these strings exactly since // they originate from the engine itself. if (arg == "--debug-agent") { if (!Debugger.IsAttached) { Debugger.Launch(); } } else if (arg.StartsWith("--trace:")) { traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), arg.Substring(8)); } } // Initialize trace so we can see what's happening int pid = Process.GetCurrentProcess().Id; string logname = string.Format(LOG_FILE_FORMAT, pid); InternalTrace.Initialize(logname, traceLevel); log.Info("Agent process {0} starting", pid); log.Info("Running under version {0}, {1}", Environment.Version, RuntimeFramework.CurrentFramework.DisplayName); // Restore the COMPLUS_Version env variable if it's been overridden by TestAgency::LaunchAgentProcess try { string cpvOriginal = Environment.GetEnvironmentVariable("TestAgency_COMPLUS_Version_Original"); if (!string.IsNullOrEmpty(cpvOriginal)) { log.Debug("Agent process has the COMPLUS_Version environment variable value \"{0}\" overridden with \"{1}\", restoring the original value.", cpvOriginal, Environment.GetEnvironmentVariable("COMPLUS_Version")); Environment.SetEnvironmentVariable("TestAgency_COMPLUS_Version_Original", null, EnvironmentVariableTarget.Process); // Erase marker Environment.SetEnvironmentVariable("COMPLUS_Version", (cpvOriginal == "NULL" ? null : cpvOriginal), EnvironmentVariableTarget.Process); // Restore original (which might be n/a) } } catch (Exception ex) { log.Warning("Failed to restore the COMPLUS_Version variable. " + ex.Message); // Proceed with running tests anyway } // Create TestEngine - this program is // conceptually part of the engine and // can access it's internals as needed. TestEngine engine = new TestEngine(); // TODO: We need to get this from somewhere. Argument? engine.InternalTraceLevel = InternalTraceLevel.Debug; // Custom Service Initialization //log.Info("Adding Services"); engine.Services.Add(new SettingsService(false)); engine.Services.Add(new ExtensionService()); engine.Services.Add(new ProjectService()); engine.Services.Add(new DomainManager()); engine.Services.Add(new InProcessTestRunnerFactory()); engine.Services.Add(new DriverService()); //engine.Services.Add( new TestLoader() ); // Initialize Services log.Info("Initializing Services"); engine.Initialize(); Channel = ServerUtilities.GetTcpChannel(); log.Info("Connecting to TestAgency at {0}", AgencyUrl); try { Agency = Activator.GetObject(typeof(ITestAgency), AgencyUrl) as ITestAgency; } catch (Exception ex) { log.Error("Unable to connect", ex); } if (Channel != null) { log.Info("Starting RemoteTestAgent"); RemoteTestAgent agent = new RemoteTestAgent(AgentId, Agency, engine.Services); try { if (agent.Start()) { log.Debug("Waiting for stopSignal"); agent.WaitForStop(); log.Debug("Stop signal received"); } else { log.Error("Failed to start RemoteTestAgent"); } } catch (Exception ex) { log.Error("Exception in RemoteTestAgent", ex); } //log.Info("Unregistering Channel"); try { ChannelServices.UnregisterChannel(Channel); } catch (Exception ex) { log.Error("ChannelServices.UnregisterChannel threw an exception", ex); } } log.Info("Agent process {0} exiting", Process.GetCurrentProcess().Id); return(0); }
private void WriteLog(InternalTraceLevel level, string message) { writer.WriteLine(TRACE_FMT, DateTime.Now.ToString(TIME_FMT), level == InternalTraceLevel.Verbose ? "Debug" : level.ToString(), #if PORTABLE System.Environment.CurrentManagedThreadId, #else System.Threading.Thread.CurrentThread.ManagedThreadId, #endif name, message); }
/// <summary> /// Create an instance of the test engine using provided values /// for the assembly and type names. This method is intended /// for use in experimenting with alternate implementations. /// </summary> /// <param name="assemblyName">The name of the assembly to be used.</param> /// <param name="typeName">The name of the Type to be used.</param> /// <returns>An ITestEngine.</returns> public static ITestEngine CreateInstance(string assemblyName, string typeName, string workDirectory, InternalTraceLevel traceLevel) { try { ITestEngine engine = (ITestEngine) AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyName, typeName); engine.InitializeServices(workDirectory, traceLevel); return(engine); } catch (Exception ex) { throw new Exception("Failed to load the test engine", ex); } }
/// <summary> /// Create an instance of the test engine using default values /// for the assembly and type names. /// </summary> /// <returns>An ITestEngine.</returns> public static ITestEngine CreateInstance(string workDirectory, InternalTraceLevel traceLevel) { return(CreateInstance(DefaultAssemblyName, DefaultTypeName, workDirectory, traceLevel)); }
private void WriteLog(InternalTraceLevel level, string message) { writer.WriteLine(TRACE_FMT, DateTime.Now.ToString(TIME_FMT), level == InternalTraceLevel.Verbose ? "Debug" : level.ToString(), System.Threading.Thread.CurrentThread.ManagedThreadId, name, message); }
private void Log(InternalTraceLevel level, string format, params object[] args) { if (InternalTrace.Level >= level) Log(level, string.Format(format, args)); }
private void Log(InternalTraceLevel level, string format, params object[] args) { if (this.maxLevel >= level) WriteLog(level, string.Format( format, args ) ); }
private void Log(InternalTraceLevel level, string message) { if (writer != null && this.maxLevel >= level) WriteLog(level, message); }
public static void Main(string[] args) { AgentId = new Guid(args[0]); AgencyUrl = args[1]; InternalTraceLevel traceLevel = InternalTraceLevel.Off; int pid = Process.GetCurrentProcess().Id; bool debugArgPassed = false; string workDirectory = string.Empty; for (int i = 2; i < args.Length; i++) { string arg = args[i]; // NOTE: we can test these strings exactly since // they originate from the engine itself. if (arg == "--debug-agent") { debugArgPassed = true; } else if (arg.StartsWith("--trace:")) { traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), arg.Substring(8)); } else if (arg.StartsWith("--pid=")) { int agencyProcessId = int.Parse(arg.Substring(6)); AgencyProcess = Process.GetProcessById(agencyProcessId); } else if (arg.StartsWith("--work=")) { workDirectory = arg.Substring(7); } } var logName = $"nunit-agent_{pid}.log"; InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel); log = InternalTrace.GetLogger(typeof(NUnitTestAgent)); if (debugArgPassed) { TryLaunchDebugger(); } log.Info("Agent process {0} starting", pid); log.Info("Running under version {0}, {1}", Environment.Version, RuntimeFramework.CurrentFramework.DisplayName); // Restore the COMPLUS_Version env variable if it's been overridden by TestAgency::LaunchAgentProcess try { string cpvOriginal = Environment.GetEnvironmentVariable("TestAgency_COMPLUS_Version_Original"); if (!string.IsNullOrEmpty(cpvOriginal)) { log.Debug("Agent process has the COMPLUS_Version environment variable value \"{0}\" overridden with \"{1}\", restoring the original value.", cpvOriginal, Environment.GetEnvironmentVariable("COMPLUS_Version")); Environment.SetEnvironmentVariable("TestAgency_COMPLUS_Version_Original", null, EnvironmentVariableTarget.Process); // Erase marker Environment.SetEnvironmentVariable("COMPLUS_Version", (cpvOriginal == "NULL" ? null : cpvOriginal), EnvironmentVariableTarget.Process); // Restore original (which might be n/a) } } catch (Exception ex) { log.Warning("Failed to restore the COMPLUS_Version variable. " + ex.Message); // Proceed with running tests anyway } // Create TestEngine - this program is // conceptually part of the engine and // can access it's internals as needed. TestEngine engine = new TestEngine(); // TODO: We need to get this from somewhere. Argument? engine.InternalTraceLevel = InternalTraceLevel.Debug; // Custom Service Initialization //log.Info("Adding Services"); engine.Services.Add(new SettingsService(false)); engine.Services.Add(new ExtensionService()); engine.Services.Add(new ProjectService()); engine.Services.Add(new DomainManager()); engine.Services.Add(new InProcessTestRunnerFactory()); engine.Services.Add(new DriverService()); // Initialize Services log.Info("Initializing Services"); engine.Initialize(); log.Info("Starting RemoteTestAgent"); Agent = new RemoteTestAgent(AgentId, AgencyUrl, engine.Services); try { if (Agent.Start()) { WaitForStop(); } else { log.Error("Failed to start RemoteTestAgent"); Environment.Exit(AgentExitCodes.FAILED_TO_START_REMOTE_AGENT); } } catch (Exception ex) { log.Error("Exception in RemoteTestAgent", ex); Environment.Exit(AgentExitCodes.UNEXPECTED_EXCEPTION); } log.Info("Agent process {0} exiting cleanly", pid); Environment.Exit(AgentExitCodes.OK); }
public static int Main(string[] args) { ExtendedConsoleOptions options = new ExtendedConsoleOptions(args); // Create SettingsService early so we know the trace level right at the start SettingsService settingsService = new SettingsService(); InternalTraceLevel level = (InternalTraceLevel)settingsService.GetSetting("Options.InternalTraceLevel", InternalTraceLevel.Default); if (options.trace != InternalTraceLevel.Default) { level = options.trace; } InternalTrace.Initialize("nunit-console_%p.log", level); log.Info("NUnit-console.exe starting"); if (!options.nologo) { WriteCopyright(); } if (options.help) { options.Help(); return(ConsoleUi.OK); } if (options.NoArgs) { Console.Error.WriteLine("fatal error: no inputs specified"); options.Help(); return(ConsoleUi.OK); } if (!options.Validate()) { foreach (string arg in options.InvalidArguments) { Console.Error.WriteLine("fatal error: invalid argument: {0}", arg); } options.Help(); return(ConsoleUi.INVALID_ARG); } // Add Standard Services to ServiceManager ServiceManager.Services.AddService(settingsService); ServiceManager.Services.AddService(new DomainManager()); //ServiceManager.Services.AddService( new RecentFilesService() ); ServiceManager.Services.AddService(new ProjectService()); //ServiceManager.Services.AddService( new TestLoader() ); ServiceManager.Services.AddService(new AddinRegistry()); ServiceManager.Services.AddService(new AddinManager()); ServiceManager.Services.AddService(new TestAgency()); // Initialize Services ServiceManager.Services.InitializeServices(); foreach (string parm in options.Parameters) { if (!Services.ProjectService.CanLoadProject(parm) && !PathUtils.IsAssemblyFileType(parm)) { Console.WriteLine("File type not known: {0}", parm); return(ConsoleUi.INVALID_ARG); } } try { ExtendedConsoleUi consoleUi = new ExtendedConsoleUi(); return(consoleUi.Execute(options)); } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); return(ConsoleUi.FILE_NOT_FOUND); } catch (Exception ex) { Console.WriteLine("Unhandled Exception:\n{0}", ex.ToString()); return(ConsoleUi.UNEXPECTED_ERROR); } finally { if (options.wait) { Console.Out.WriteLine("\nHit <enter> key to continue"); Console.ReadLine(); } log.Info("NUnit-console.exe terminating"); } }
/// <summary> /// Execute a test run based on the aruments passed /// from Main. /// </summary> /// <param name="args">An array of arguments</param> public void Execute(string[] args) { // NOTE: Execute must be directly called from the // test assembly in order for the mechanism to work. _options = new CommandLineOptions(args); _workDirectory = _options.WorkDirectory; if (_workDirectory == null) { _workDirectory = Environment.CurrentDirectory; } else if (!Directory.Exists(_workDirectory)) { Directory.CreateDirectory(_workDirectory); } #if !SILVERLIGHT if (_options.DisplayTeamCityServiceMessages) { _teamCity = new TeamCityEventListener(); } if (_options.OutFile != null) { _outWriter = new StreamWriter(Path.Combine(_workDirectory, _options.OutFile)); Console.SetOut(_outWriter); } if (_options.ErrFile != null) { _errWriter = new StreamWriter(Path.Combine(_workDirectory, _options.ErrFile)); Console.SetError(_errWriter); } #endif if (!_options.NoHeader) { WriteHeader(_outWriter); } if (_options.ShowHelp) { _outWriter.Write(_options.HelpText); } else if (_options.ErrorMessages.Count > 0) { foreach (string line in _options.ErrorMessages) { _outWriter.WriteLine(line); } _outWriter.WriteLine(_options.HelpText); } else { Assembly callingAssembly = Assembly.GetCallingAssembly(); // We must call this before creating the runner so that any internal logging is initialized InternalTraceLevel level = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), _options.InternalTraceLevel, true); InitializeInternalTrace(callingAssembly.Location, level); _runner = new NUnitLiteTestAssemblyRunner(new DefaultTestAssemblyBuilder()); DisplayRequestedOptions(_outWriter); WriteRuntimeEnvironment(_outWriter); if (_options.Wait && _options.OutFile != null) { _outWriter.WriteLine("Ignoring /wait option - only valid for Console"); } var runSettings = MakeRunSettings(_options); TestFilter filter = CreateTestFilter(_options); try { foreach (string name in _options.InputFiles) { _assemblies.Add(Assembly.Load(name)); } if (_assemblies.Count == 0) { _assemblies.Add(callingAssembly); } // TODO: For now, ignore all but first assembly Assembly assembly = _assemblies[0]; //Randomizer.InitialSeed = _commandLineOptions.InitialSeed; if (_runner.Load(assembly, runSettings) == null) { var assemblyName = AssemblyHelper.GetAssemblyName(assembly); Console.WriteLine("No tests found in assembly {0}", assemblyName.Name); return; } if (_options.Explore) { ExploreTests(); } else { RunTests(filter); } } catch (FileNotFoundException ex) { _outWriter.WriteLine(ex.Message); } catch (Exception ex) { _outWriter.WriteLine(ex.ToString()); } finally { if (_options.OutFile == null) { if (_options.Wait) { Console.WriteLine("Press Enter key to continue . . ."); Console.ReadLine(); } } else { _outWriter.Close(); } if (_options.ErrFile != null) { _errWriter.Close(); } } } }
public static void Log(InternalTraceLevel level, string message, string category, Exception ex) { Writer.WriteLine("{0} {1,-5} [{2,2}] {3}: {4}", DateTime.Now.ToString(TIME_FMT), level == InternalTraceLevel.Verbose ? "Debug" : level.ToString(), #if NET_2_0 System.Threading.Thread.CurrentThread.ManagedThreadId, #else AppDomain.GetCurrentThreadId(), #endif category, message); if (ex != null) Writer.WriteLine(ex.ToString()); }
public void Log(InternalTraceLevel level, string message) { if (InternalTrace.Level >= level) InternalTrace.Log(level, message, name); }