public static IEasyNetQLogger GetLogType() { if (LogType == "ConsoleLogger") { return(new ConsoleLogger()); } else if (LogType == "DelegateLogger") { var delelog = new DelegateLogger(); delelog.DebugWriteDelegate = (a, b) => { Log.WriteLog("Debug:" + a); }; delelog.ErrorWriteDelegate = (a, b) => { Log.WriteLog("Error:" + a); }; delelog.InfoWriteDelegate = (a, b) => { Log.WriteLog("Info:" + a); }; return(delelog); } else if (LogType == "NullLogger") { return(new NullLogger()); } else { return(new NullLogger()); } }
/// <summary> /// Fügt eine Logger-Action zur asynchronen Ausführung der Instanz in <see cref="ModuleShell.Logger" /> hinzu. /// </summary> /// <param name="action">Die Action, die hinzugefügt werden soll.</param> /// <returns>Diese Instanz.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="action" /> ist <see langword="null" />. /// </exception> public ModuleShell AddAsyncLoggerAction(Action <ILogMessage> action) { var delegateLogger = new DelegateLogger(); delegateLogger.Add(action); return(this.AddAsyncLogger(delegateLogger)); }
private async Task EnsureMinNuGetVersionAsync(string nuGetExePath, ILogger logger) { void NullLogger(string message, string category) { } var standardOut = new List <string>(); ILogger versionLogger = new DelegateLogger( (message, category) => standardOut.Add(message), NullLogger, NullLogger); IEnumerable <string> args = new List <string>(); ExitCode versionExitCode = await ProcessHelper.ExecuteAsync(nuGetExePath, args, versionLogger); if (!versionExitCode.IsSuccess) { logger.WriteWarning($"NuGet version exit code was {versionExitCode}"); return; } string nugetVersion = "NuGet Version: "; string versionLine = standardOut.FirstOrDefault( line => line.StartsWith(nugetVersion, StringComparison.InvariantCultureIgnoreCase)); if (string.IsNullOrWhiteSpace(versionLine)) { logger.WriteWarning("Could not ensure NuGet version, no version line in NuGet output"); return; } char majorNuGetVersion = versionLine.Substring(nugetVersion.Length).FirstOrDefault(); if (majorNuGetVersion == '2') { IEnumerable <string> updateSelfArgs = new List <string> { "update", "-self" }; ExitCode exitCode = await ProcessHelper.ExecuteAsync(nuGetExePath, updateSelfArgs, logger); if (!exitCode.IsSuccess) { logger.WriteWarning($"The NuGet version could not be determined, exit code {exitCode}"); } return; } if (majorNuGetVersion != '3') { logger.WriteWarning( $"NuGet version could not be determined, major version starts with character {majorNuGetVersion}"); return; } logger.WriteVerbose($"NuGet major version is {majorNuGetVersion}"); }
public PublisherConfirmsIntegrationTests() { var dlogger = new DelegateLogger { InfoWriteDelegate = (s, o) => Console.WriteLine(s, o), ErrorWriteDelegate = (s, o) => Console.WriteLine(s, o) }; var logger = new ConsoleLogger(); bus = RabbitHutch.CreateBus("host=localhost;publisherConfirms=true;timeout=10", x => x.Register <IEasyNetQLogger>(_ => dlogger)); }
public static int Main(string[] args) { var errorCount = 0; var localLogger = new DelegateLogger(DefaultLogger.Instance) { ErrorHandler = message => { ++errorCount; DefaultLogger.Instance.Error(message); } }; Execute(args, localLogger); return(errorCount != 0 ? 1 : 0); }
public MainForm() { InitializeComponent(); _logger = new DelegateLogger( (t, f, m) => { if (InvokeRequired) Invoke(new Action<LogLevel, string, string>(Log), t, f, m); else Log(t, f, m); }, LogLevel.Diagnostic); _server = new Server(_logger); LogLevelControl.DataSource = Enum.GetValues(typeof (LogLevel)); LogLevelControl.DataBindings.Add("SelectedItem", _logger, "Level"); LogLevelControl.SelectionChangeCommitted += (e, s) => { _logger.Level = (LogLevel)LogLevelControl.SelectedItem; }; }
private static int Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; var loggerFuncs = new DelegateLogger(); loggerFuncs.Add(WriteLogMessageToConsole); var logger = new AggregateLogger(); logger.Add(loggerFuncs); try { using (var server = new ApplicationServer()) { if (!server.IsInitialized) { GlobalConsole.Current.WriteLine("Initializing server... "); var srvCtx = new SimpleAppServerContext(server); var initCtx = new SimpleAppServerInitContext(); initCtx.Arguments = args; initCtx.Logger = logger; initCtx.ServerContext = srvCtx; foreach (var a in args) { if (a.ToLower().Trim().StartsWith("/rootdir:")) { // custom root/working directory initCtx.WorkingDirectory = new DirectoryInfo(a.Substring(a.IndexOf(':') + 1) .TrimStart()).FullName; } } server.Initialize(initCtx); GlobalConsole.Current.WriteLine("Server has been initialized."); srvCtx.InnerServiceLocator = server.GlobalServiceLocator; } GlobalConsole.Current.WriteLine("Starting server... "); server.Start(); GlobalConsole.Current.WriteLine("Server has been started."); IMenuHandler currentMenu = new RootMenu(); string line; while (true) { if (currentMenu == null) { break; } GlobalConsole.Current.Clear(); currentMenu.DrawMenu(); var inputIsValid = false; while (!inputIsValid) { GlobalConsole.Current.WriteLine(); GlobalConsole.Current.Write("> "); if (currentMenu.WaitsForInput) { line = GlobalConsole.Current.ReadLine(); } else { line = null; } IMenuHandler temp; if (!(inputIsValid = currentMenu.HandleInput(line, out temp))) { GlobalConsole.Current.WriteLine(); GlobalConsole.Current.WriteLine("Invalid input!"); } else { currentMenu = temp; } } } GlobalConsole.Current.Write("Shutting down server... "); } GlobalConsole.Current.WriteLine("[OK]"); return(0); } catch (Exception ex) { GlobalConsole.Current .WriteLine(ex.GetBaseException() ?? ex); return(1); } }
private static void Test_ValueRouter(dynamic test = null, bool test3 = false, string test2 = "wurst") { Console.WriteLine(Thread.CurrentThread.ManagedThreadId); var logger = new DelegateLogger(); logger.Add((msg) => { Console.WriteLine("\t" + msg.Thread.ManagedThreadId); Console.WriteLine("\t" + Thread.CurrentThread.ManagedThreadId); }); var taskLogger = new TaskLogger(logger, TaskScheduler.Current); var a1 = new EnumValueRouter <TrafficLightState>(TrafficLightState.Yellow); var b1 = new EnumValueRouter <TrafficLightState>(); var b2 = new EnumValueRouter <TrafficLightState>(); var c1 = new EnumValueRouter <TrafficLightState>(); var c2 = new EnumValueRouter <TrafficLightState>(); var c3 = new EnumValueRouter <TrafficLightState>(); // Struktur festlegen { a1.AddMediator(b1); a1.AddMediator(b2); b1.AddMediator(c1); b1.AddMediator(c2); b2.AddMediator(c3); } c1.MyValue = TrafficLightState.Green; b1.MyValue = TrafficLightState.None; c3.MyValue = TrafficLightState.Red; c3.MyDescription = "es gibt lecker wurst"; c3.MyTitle = "!!!WURST!!!"; Console.WriteLine(a1.RoutedDescription); taskLogger.Log(c3, LoggerFacadeCategories.Warnings | LoggerFacadeCategories.Errors); var xmlLogger = new XmlFileLogger(@"D:\logfiles"); //try //{ // throw new Exception("test"); //} //catch (Exception ex) //{ // xmlLogger.Log(ex, // LoggerFacadeCategories.Warnings | LoggerFacadeCategories.Errors); //} //var tasks = Enumerable.Range(0, 999) // .Select(i => Task.Factory.StartNew((state) => // { // var xl = (XmlFileLogger)state; // xmlLogger.Log(new Exception(), // LoggerFacadeCategories.Warnings | LoggerFacadeCategories.Errors); // }, xmlLogger)) // .ToArray(); //Task.WaitAll(tasks); }
// Protected Methods (3) /// <summary> /// /// </summary> /// <see cref="AppServerBase.OnInitialize(IAppServerInitContext, ref bool)" /> protected override void OnInitialize(IAppServerInitContext initContext, ref bool isInitialized) { this.Arguments = (initContext.Arguments ?? Enumerable.Empty <string>()).OfType <string>() .ToArray(); this.WorkingDirectory = initContext.WorkingDirectory; if (string.IsNullOrWhiteSpace(this.WorkingDirectory)) { this.WorkingDirectory = Environment.CurrentDirectory; } this.StartupConfig = new IniFileConfigRepository(Path.Combine(this.WorkingDirectory, "config.ini"), false); var trustedAssemblyKeys = this.LoadTrustedAssemblyKeyList(); this.EntityAssemblies = new SynchronizedCollection <Assembly>(); this.RefreshEntityAssemblyList(); // service locator CompositionContainer compContainer; AggregateCatalog compCatalog; DelegateServiceLocator serviceLocator; { compCatalog = new AggregateCatalog(); compCatalog.Catalogs .Add(this.TrustedCompositionCatalog = new StrongNamedAssemblyPartCatalog(trustedAssemblyKeys)); this.ReinitTrustedCompositionCatalog(); compContainer = new CompositionContainer(compCatalog, isThreadSafe: true); var mefServiceLocator = new ExportProviderServiceLocator(compContainer); serviceLocator = new DelegateServiceLocator(mefServiceLocator); serviceLocator.RegisterSingleProvider <global::MarcelJoachimKloubert.CLRToolbox.Templates.Text.Html.IHtmlTemplate>(WebInterfaceHandler.GetHtmlTemplate); } // logger AggregateLogger logger; DelegateLogger loggerFuncs; { loggerFuncs = new DelegateLogger(); logger = new AggregateLogger(); logger.Add(loggerFuncs); var outerLogger = initContext.Logger; if (outerLogger != null) { logger.Add(outerLogger); } serviceLocator.RegisterMultiProvider(this.GetAllLoggers, false); compContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CLRToolbox.Diagnostics.ILoggerFacade>(new AsyncLogger(logger)); } this.LoggerFuncs = loggerFuncs; this.Logger = logger; this.GlobalCompositionCatalog = compCatalog; this.GlobalCompositionContainer = compContainer; compContainer.ComposeExportedValue <global::MarcelJoachimKloubert.ApplicationServer.ApplicationServer>(this); compContainer.ComposeExportedValue <global::MarcelJoachimKloubert.ApplicationServer.IAppServer>(this); this.GlobalServiceLocator = serviceLocator; ServiceLocator.SetLocatorProvider(this.GetGlobalServiceLocator); }
// Protected Methods (2) /// <summary> /// /// </summary> /// <see cref="ServiceBase.OnStart(string[])" /> protected override void OnStart(string[] args) { var asmDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); TimeSpan?startDelay = null; var workDir = asmDir; foreach (var a in args) { if (a.ToLower().Trim().StartsWith("/rootdir:")) { // custom root/working directory var dir = new DirectoryInfo(a.Substring(a.IndexOf(':') + 1) .TrimStart()).FullName; if (Path.IsPathRooted(dir)) { workDir = new DirectoryInfo(dir).CreateDirectoryDeep().FullName; } else { workDir = new DirectoryInfo(Path.Combine(asmDir, dir)).CreateDirectoryDeep().FullName; } } else if (a.ToLower().Trim().StartsWith("/startdelay:")) { var seconds = a.Substring(a.IndexOf(':') + 1) .Trim(); if (seconds == string.Empty) { seconds = "15"; } startDelay = TimeSpan.FromSeconds(double.Parse(seconds, CultureInfo.InvariantCulture)); } } if (startDelay.HasValue) { Thread.Sleep(startDelay.Value); } this.EventLog .WriteEntry(string.Format("Root directory is: {0}", workDir), EventLogEntryType.Information); this.LogDirectory = new DirectoryInfo(Path.Combine(workDir, "logs")).CreateDirectoryDeep() .FullName; this.EventLog .WriteEntry(string.Format("Log directory is: {0}", this.LogDirectory), EventLogEntryType.Information); GlobalConsole.SetConsole(new ServiceConsole(this)); var loggerFuncs = new DelegateLogger(); loggerFuncs.Add(this.WriteEventLogMessage); var logger = new AggregateLogger(); logger.Add(new AsyncLogger(loggerFuncs)); var server = new ApplicationServer(); try { if (!server.IsInitialized) { var srvCtx = new SimpleAppServerContext(server); var initCtx = new SimpleAppServerInitContext(); initCtx.Arguments = args; initCtx.Logger = logger; initCtx.ServerContext = srvCtx; initCtx.WorkingDirectory = workDir; try { server.Initialize(initCtx); this.EventLog .WriteEntry("Server has been initialized.", EventLogEntryType.Information); } catch (Exception ex) { this.EventLog .WriteEntry(string.Format("Server could not be initialized!{0}{0}{1}", Environment.NewLine, ex.GetBaseException() ?? ex), EventLogEntryType.Error); throw; } srvCtx.InnerServiceLocator = server.GlobalServiceLocator; } try { server.Start(); this.EventLog .WriteEntry("Server has been started.", EventLogEntryType.Information); } catch (Exception ex) { this.EventLog .WriteEntry(string.Format("Server could not be started!{0}{0}{1}", Environment.NewLine, ex.GetBaseException() ?? ex), EventLogEntryType.Error); throw; } this.Server = server; } catch { server.Dispose(); throw; } }