public static void InitLogger()
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();

            var patternLayout =
                new PatternLayout
            {
                ConversionPattern = "%date [%thread] %-5level %logger - %message%newline"
            };

            patternLayout.ActivateOptions();

            var roller = new RollingFileAppender
            {
                AppendToFile       = true,
                File               = $"{@"Logs\Log"}{DateTime.Now.ToString("yy-MM-dd")}.txt",
                Layout             = patternLayout,
                MaxSizeRollBackups = 5,
                MaximumFileSize    = "1MB",
                RollingStyle       = RollingFileAppender.RollingMode.Size,
                StaticLogFileName  = true
            };

            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            var memory = new MemoryAppender();

            memory.ActivateOptions();
            hierarchy.Root.AddAppender(memory);

            var consoleAppender = new ConsoleAppender();

            consoleAppender.ActivateOptions();
            hierarchy.Root.AddAppender(consoleAppender);

            hierarchy.Root.Level = Level.All;
            hierarchy.Configured = true;
        }
    static void Main()
    {
        #region ConfigureLog4Net
        PatternLayout layout = new PatternLayout
        {
            ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"
        };
        layout.ActivateOptions();
        ConsoleAppender consoleAppender = new ConsoleAppender
        {
            Threshold = Level.Info,
            Layout    = layout
        };
        // Note that ActivateOptions is required in NSB 5 and above
        consoleAppender.ActivateOptions();
        BasicConfigurator.Configure(consoleAppender);
        #endregion

        #region UseConfig

        LogManager.Use <Log4NetFactory>();

        // Then continue with your bus configuration
        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.Logging.Log4NetCustom");

        #endregion

        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.EnableInstallers();
        busConfiguration.UsePersistence <InMemoryPersistence>();

        using (IBus bus = Bus.Create(busConfiguration).Start())
        {
            bus.SendLocal(new MyMessage());
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Exemple #3
0
        /// <summary>
        /// 使用文本记录信息
        /// </summary>
        /// <Author>焰尾迭</Author>
        /// <date>2015-09-22</date>
        private static void LoadFileAppender(ILoggerRepository repository)
        {
            //string txtLogPath = FileHelper.GetAbsolutePath(string.Format("/Logs/{0}.log", repository.Name));
            string txtLogPath = string.Format(@"Logs\{0}\", repository.Name);
            RollingFileAppender fileAppender = new RollingFileAppender();

            fileAppender.Name               = "LogFileAppender";
            fileAppender.File               = txtLogPath;
            fileAppender.AppendToFile       = true;
            fileAppender.MaxSizeRollBackups = 100;
            fileAppender.MaximumFileSize    = "1MB";
            fileAppender.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;
            fileAppender.DatePattern        = "'log-" + repository.Name + "-'yyyyMMddHH'.log'";
            fileAppender.StaticLogFileName  = false;
            fileAppender.RollingStyle       = RollingFileAppender.RollingMode.Date;

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%-5p %d [%c] %m%n";
            patternLayout.ActivateOptions();
            fileAppender.Layout = patternLayout;

            //选择UTF8编码,确保中文不乱码。
            fileAppender.Encoding = Encoding.UTF8;
            fileAppender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(repository, fileAppender);

            ConsoleAppender consoleAppender = new ConsoleAppender();

            fileAppender.Name = "ConsoleAppender";
            PatternLayout patternLayout1 = new PatternLayout();

            patternLayout1.ConversionPattern = "%d [%t] %-5p %m%n";
            patternLayout1.ActivateOptions();
            consoleAppender.Layout = patternLayout1;
            consoleAppender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(repository, consoleAppender);
        }
        public static void Configure(TestContext Context)
        {
            Debug.WriteLine("Starting log4net setup and configuration");

            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            hierarchy.Root.RemoveAllAppenders();

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            patternLayout.ActivateOptions();

            FileAppender fileAppender = new FileAppender();

            fileAppender.Name         = "Integration Test FileAppender";
            fileAppender.File         = @"Logs\IntegrationTest.log";
            fileAppender.AppendToFile = false;
            fileAppender.Layout       = patternLayout;
            fileAppender.ActivateOptions();
            hierarchy.Root.AddAppender(fileAppender);

            ConsoleAppender consoleAppender = new ConsoleAppender();

            consoleAppender.Name   = "Integration Test ConsoleAppender";
            consoleAppender.Target = Console.Out.ToString();
            consoleAppender.ActivateOptions();
            consoleAppender.Layout = patternLayout;
            hierarchy.Root.AddAppender(consoleAppender);

            hierarchy.Root.Level = Level.Debug;
            hierarchy.Configured = true;

            log = LogManager.GetLogger(typeof(AssemblyInitializer));
            log.Debug("log4net initialized for Integration Test");

            Debug.WriteLine("Completed log4net setup and configuration");
        }
Exemple #5
0
        public App()
        {
            InitializeComponent();

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            log4net.Repository.Hierarchy.Hierarchy hierarchy =
                (Hierarchy)log4net.LogManager.GetRepository(Assembly.GetAssembly(typeof(App)));

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "[%thread] %-5level %logger - %message";
            patternLayout.ActivateOptions();

            var cca = new ConsoleAppender();

            cca.Layout = patternLayout;
            cca.ActivateOptions();
            hierarchy.Root.AddAppender(cca);

            hierarchy.Root.Level = Level.Debug;
            hierarchy.Configured = true;

            {
                var config = new NLog.Config.LoggingConfiguration();

                // Targets where to log to: File and Console
                var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

                // Rules for mapping loggers to targets
                // config.AddRule(LogLevel.Warn, LogLevel.Fatal, logconsole);

                // Apply config
                NLog.LogManager.Configuration = config;
            }

            MainPage = new MainPage();
        }
        private static void ConfigureLogger()
        {
            ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());

            PatternLayout timeLayout = new PatternLayout();

            timeLayout.ConversionPattern = "%utcdate %level %logger: %message%newline";
            timeLayout.ActivateOptions();

            PatternLayout noTimeLayout = new PatternLayout();

            noTimeLayout.ConversionPattern = "%level %logger: %message%newline";
            noTimeLayout.ActivateOptions();

            ConsoleAppender consoleAppender = new ConsoleAppender();

            consoleAppender.Layout = timeLayout;
            consoleAppender.ActivateOptions();

            // Not sure about usage of this.
            PatternLayout identity = new PatternLayout();

            identity.ConversionPattern = "log4net";
            identity.ActivateOptions();

            RemoteSyslogAppender remoteSyslogAppender = new RemoteSyslogAppender();

            remoteSyslogAppender.Layout        = noTimeLayout;
            remoteSyslogAppender.RemoteAddress = GetIpv4Address("f00.lv");
            remoteSyslogAppender.RemotePort    = 514;
            remoteSyslogAppender.Facility      = RemoteSyslogAppender.SyslogFacility.User;
            remoteSyslogAppender.Identity      = identity;
            remoteSyslogAppender.ActivateOptions();

            IBasicRepositoryConfigurator configurableRepository = repository as IBasicRepositoryConfigurator;

            configurableRepository.Configure(remoteSyslogAppender, consoleAppender);
        }
Exemple #7
0
        public static void Setup()
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date [%thread] %-5level - %message%newline";
            patternLayout.ActivateOptions();

            roller = new RollingFileAppender();
            roller.AppendToFile       = false;
            roller.File               = Path.Combine(Directory.GetCurrentDirectory(), logFilePath);
            roller.Layout             = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize    = "1GB";
            roller.RollingStyle       = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName  = true;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            ConsoleAppender console = new ConsoleAppender();

            console.Layout = patternLayout;
            console.ActivateOptions();
            hierarchy.Root.AddAppender(console);

            MemoryAppender memory = new MemoryAppender();

            memory.ActivateOptions();
            hierarchy.Root.AddAppender(memory);

            guiDebugConsoleAppender = new GUIDebugConsoleAppender();
            guiDebugConsoleAppender.ActivateOptions();
            hierarchy.Root.AddAppender(guiDebugConsoleAppender);

            hierarchy.Root.Level = Level.Info;
            hierarchy.Configured = true;
        }
Exemple #8
0
        public void SetupLogging()
        {
            var appender = new ConsoleAppender();
            var layout   = new PatternLayout()
            {
                ConversionPattern = "%6level [%3thread] %-20.20logger{1} - %message%newline%exception"
            };

            layout.ActivateOptions();
            appender.Layout = layout;
            appender.ActivateOptions();
            if (LogFile != null)
            {
                var fileAppender = new RollingFileAppender()
                {
                    File               = LogFile.FullName,
                    Layout             = layout,
                    MaximumFileSize    = "1MB",
                    MaxSizeRollBackups = 10,
                    RollingStyle       = RollingFileAppender.RollingMode.Size
                };
                fileAppender.ActivateOptions();
                BasicConfigurator.Configure(appender, fileAppender);
            }
            else
            {
                BasicConfigurator.Configure(appender);
            }

            var repo  = LogManager.GetRepository();
            var level = repo.LevelMap[LogLevel.ToUpper()];

            if (level == null)
            {
                throw new GetOptException("Invalid log level");
            }
            repo.Threshold = level;
        }
Exemple #9
0
        public App()
        {
            InitializeComponent();

            log4net.Repository.Hierarchy.Hierarchy hierarchy =
                (Hierarchy)log4net.LogManager.GetRepository(Assembly.GetAssembly(typeof(App)));

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            patternLayout.ActivateOptions();

            var cca = new ConsoleAppender();

            cca.Layout = patternLayout;
            cca.ActivateOptions();
            hierarchy.Root.AddAppender(cca);

            hierarchy.Root.Level = Level.Debug;
            hierarchy.Configured = true;

            MainPage = new MainPage();
        }
Exemple #10
0
        private static void ConfigureLogger()
        {
            ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());

            if (repository.Configured)
            {
                throw new System.Exception("Configured already");
            }

            PatternLayout layout = new PatternLayout();

            layout.ConversionPattern = "%utcdate %level %logger: %message%newline";
            layout.ActivateOptions();

            ConsoleAppender appender = new ConsoleAppender();

            appender.Layout = layout;
            appender.ActivateOptions();

            IBasicRepositoryConfigurator configurableRepository = repository as IBasicRepositoryConfigurator;

            configurableRepository.Configure(appender);
        }
Exemple #11
0
        private static IAppender GetConsoleAppender(string loggerName, ConfigSource config, Level level)
        {
            ConsoleAppender appender = new ConsoleAppender();

            appender.Name      = loggerName;
            appender.Threshold = level;

            string target = config.GetString("target");

            if (target == "out" || target == "stdout" || target == null)
            {
                target = "Console.Out";
            }
            if (target == "err" || target == "stderr")
            {
                target = "Console.Error";
            }
            appender.Target = target;

            ConfigPattern(appender, config);
            appender.ActivateOptions();
            return(appender);
        }
Exemple #12
0
        internal static IDisposable InitLog4Net()
        {
            var asyncAppender = new AsyncAppender();
            var appender      = new ConsoleAppender
            {
                Layout =
                    new PatternLayout(
                        string.Format("run#{0}: %r %-5level - %message (%logger) [%thread]%newline", counter++)),
                Threshold = Level.Trace
            };

            appender.ActivateOptions();
            asyncAppender.AddAppender(appender);
            asyncAppender.ActivateOptions();

            // Configure the root logger.
            var h          = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();
            var rootLogger = h.Root;

            rootLogger.Level = h.LevelMap["TRACE"];
            BasicConfigurator.Configure(appender);
            return(new LogWrapper());
        }
Exemple #13
0
    public Log4NetFiltering()
    {
        #pragma warning disable CS0618 // Type or member is obsolete
        #region Log4NetFilterUsage

        var appender = new ConsoleAppender
        {
            Threshold = Level.Debug,
            Layout    = new SimpleLayout(),
        };

        appender.AddFilter(new NServiceBusLogFilter());
        appender.ActivateOptions();

        var executingAssembly = Assembly.GetExecutingAssembly();
        var repository        = log4net.LogManager.GetRepository(executingAssembly);
        BasicConfigurator.Configure(repository, appender);

        NServiceBus.Logging.LogManager.Use <Log4NetFactory>();

        #endregion
        #pragma warning restore CS0618 // Type or member is obsolete
    }
Exemple #14
0
        /// <summary>
        /// Start logging to the console.
        /// </summary>
        public static void StartConsoleLogging()
        {
#if logging
            ILoggerRepository repository = GetRootRepository();

            // Create the layout
            PatternLayout layout = new PatternLayout();
            layout.ConversionPattern = PatternLayout.DetailConversionPattern;
            layout.ActivateOptions();

            // Create the appender
            ConsoleAppender appender = new ConsoleAppender();
            appender.Layout = layout;
            appender.ActivateOptions();

            // Now use it on the root repository
            IBasicRepositoryConfigurator configurableRepository = repository as IBasicRepositoryConfigurator;
            if (configurableRepository != null)
            {
                configurableRepository.Configure(appender);
            }
#endif
        }
Exemple #15
0
        public Usage()
        {
            #region Log4NetInCode

            PatternLayout layout = new PatternLayout
            {
                ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"
            };
            layout.ActivateOptions();
            ConsoleAppender consoleAppender = new ConsoleAppender
            {
                Threshold = Level.Debug,
                Layout    = layout
            };
            // Note that ActivateOptions is required in NSB 5 and above
            consoleAppender.ActivateOptions();

            BasicConfigurator.Configure(consoleAppender);

            LogManager.Use <Log4NetFactory>();

            #endregion
        }
        /// <summary>
        /// Initializes the <see cref="ILoggerRepository"/> with a default configuration.
        /// </summary>
        /// <param name="repository">The repository to configure.</param>
        /// <remarks>
        /// <para>
        /// Initializes the specified repository using a <see cref="ConsoleAppender"/>
        /// that will write to <c>Console.Out</c>. The log messages are
        /// formatted using the <see cref="PatternLayout"/> layout object
        /// with the <see cref="PatternLayout.DetailConversionPattern"/>
        /// layout style.
        /// </para>
        /// </remarks>
        static public ICollection Configure(ILoggerRepository repository)
        {
            ArrayList configurationMessages = new ArrayList();

            using (new LogLog.LogReceivedAdapter(configurationMessages))
            {
                // Create the layout
                PatternLayout layout = new PatternLayout();
                layout.ConversionPattern = PatternLayout.DetailConversionPattern;
                layout.ActivateOptions();

                // Create the appender
                ConsoleAppender appender = new ConsoleAppender();
                appender.Layout = layout;
                appender.ActivateOptions();

                InternalConfigure(repository, appender);
            }

            repository.ConfigurationMessages = configurationMessages;

            return(configurationMessages);
        }
        public static void Setup()
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetEntryAssembly());

            var patternLayout = new PatternLayout
            {
                ConversionPattern = "%date [%thread] %-5level %logger - %message%newline"
            };

            patternLayout.ActivateOptions();

            /*
             * var roller = new RollingFileAppender
             * {
             *  AppendToFile = false,
             *  File = @"Logs\log.txt",
             *  Layout = patternLayout,
             *  MaxSizeRollBackups = 5,
             *  MaximumFileSize = "1GB",
             *  RollingStyle = RollingFileAppender.RollingMode.Size,
             *  StaticLogFileName = true
             * };
             * roller.ActivateOptions();
             * hierarchy.Root.AddAppender(roller);
             */

            var console = new ConsoleAppender
            {
                Layout = patternLayout
            };

            console.ActivateOptions();
            hierarchy.Root.AddAppender(console);

            hierarchy.Root.Level = Level.All;
            hierarchy.Configured = true;
        }
Exemple #18
0
        /// <summary>
        /// 使用文本文件记录异常日志
        /// </summary>
        public static void LoadFileAppender()
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;

            currentPath = Path.Combine(currentPath, @"Log");
            string txtLogPath = Path.Combine(currentPath, "Log-" + DateTime.Now.ToString("yyyyMMdd") + ".txt");

            log4net.Repository.Hierarchy.Hierarchy hier =
                (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();
            if (hier != null)
            {
                FileAppender fileAppender = new FileAppender();
                fileAppender.Name         = "LogFileAppender";
                fileAppender.File         = txtLogPath;
                fileAppender.AppendToFile = true;
                PatternLayout patternLayout = new PatternLayout
                {
                    ConversionPattern =
                        "%date [%thread] %-5level %logger - %message%newline"
                        //[%property{log4net:HostName}]
                };
                patternLayout.ActivateOptions();
                fileAppender.Layout       = patternLayout;
                fileAppender.Encoding     = Encoding.UTF8;
                fileAppender.LockingModel = new FileAppender.MinimalLock();
                fileAppender.ActivateOptions();

                log4net.Config.BasicConfigurator.Configure(fileAppender);

                // add console appender
                ConsoleAppender conAppender = new ConsoleAppender();
                conAppender.Name   = "Console";
                conAppender.Layout = patternLayout;
                conAppender.ActivateOptions();
                log4net.Config.BasicConfigurator.Configure(conAppender);
            }
        }
Exemple #19
0
        public static void Setup()
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();

            roller.AppendToFile       = false;
            roller.File               = @"Logs\EventLog.txt";
            roller.Layout             = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize    = "1GB";
            roller.RollingStyle       = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName  = true;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            MemoryAppender memory = new MemoryAppender();

            memory.ActivateOptions();
            hierarchy.Root.AddAppender(memory);

            ConsoleAppender consoleAppender = new ConsoleAppender();

            consoleAppender.Layout = patternLayout;
            consoleAppender.ActivateOptions();

            hierarchy.Root.AddAppender(consoleAppender);

            hierarchy.Root.Level = Level.All;
            hierarchy.Configured = true;
        }
Exemple #20
0
    Usage()
    {
        #region Log4NetInCode

        var layout = new PatternLayout
        {
            ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"
        };
        layout.ActivateOptions();
        var consoleAppender = new ConsoleAppender
        {
            Threshold = Level.Debug,
            Layout    = layout
        };
        consoleAppender.ActivateOptions();

        var executingAssembly = Assembly.GetExecutingAssembly();
        var repository        = log4net.LogManager.GetRepository(executingAssembly);
        BasicConfigurator.Configure(repository, consoleAppender);

        LogManager.Use <Log4NetFactory>();

        #endregion
    }
Exemple #21
0
        private static void ConfigureDebugLogging()
        {
            if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config")))
            {
                return;                // that overrides the default config
            }
            var loggerRepository = LogManager.GetRepository(typeof(HttpServer).Assembly);

            var patternLayout   = new PatternLayout(PatternLayout.DefaultConversionPattern);
            var consoleAppender = new ConsoleAppender
            {
                Layout = patternLayout,
            };

            consoleAppender.ActivateOptions();
            ((Logger)loggerRepository.GetLogger(typeof(HttpServer).FullName)).AddAppender(consoleAppender);
            var fileAppender = new RollingFileAppender
            {
                AppendToFile       = false,
                File               = "Raven.Server.log",
                Layout             = patternLayout,
                MaxSizeRollBackups = 3,
                MaximumFileSize    = "1024KB",
                StaticLogFileName  = true,
                LockingModel       = new FileAppender.MinimalLock()
            };

            fileAppender.ActivateOptions();

            var asyncBufferingAppender = new AsyncBufferingAppender();

            asyncBufferingAppender.AddAppender(fileAppender);

            ((Hierarchy)loggerRepository).Root.AddAppender(asyncBufferingAppender);
            loggerRepository.Configured = true;
        }
    async Task AsyncOnStart()
    {
        #region logging

        var layout = new PatternLayout
        {
            ConversionPattern = "%d %-5p %c - %m%n"
        };
        layout.ActivateOptions();
        var appender = new ConsoleAppender
        {
            Layout    = layout,
            Threshold = Level.Info
        };
        appender.ActivateOptions();

        BasicConfigurator.Configure(appender);

        LogManager.Use <Log4NetFactory>();

        #endregion

        #region create-config

        var endpointConfiguration = new EndpointConfiguration("Samples.FirstEndpoint");

        #endregion

        #region container

        var builder = new ContainerBuilder();
        // configure custom services
        // builder.RegisterInstance(new MyService());
        var container = builder.Build();
        endpointConfiguration.UseContainer <AutofacBuilder>(
            customizations: customizations =>
        {
            customizations.ExistingLifetimeScope(container);
        });

        #endregion

        #region serialization

        endpointConfiguration.UseSerialization <XmlSerializer>();

        #endregion

        #region error

        endpointConfiguration.SendFailedMessagesTo("error");

        #endregion

        #region audit

        endpointConfiguration.AuditProcessedMessagesTo("audit");

        #endregion

        #region transport

        endpointConfiguration.UseTransport <LearningTransport>();

        #endregion

        #region persistence

        endpointConfiguration.UsePersistence <LearningPersistence>();

        #endregion

        #region critical-errors

        endpointConfiguration.DefineCriticalErrorAction(
            onCriticalError: async context =>
        {
            // Log the critical error
            log.Fatal($"CRITICAL: {context.Error}", context.Exception);

            await context.Stop()
            .ConfigureAwait(false);

            // Kill the process on a critical error
            var output = $"NServiceBus critical error:\n{context.Error}\nShutting down.";
            Environment.FailFast(output, context.Exception);
        });

        #endregion

        #region start-bus

        endpointConfiguration.EnableInstallers();
        endpointInstance = await Endpoint.Start(endpointConfiguration)
                           .ConfigureAwait(false);

        #endregion

        var myMessage = new MyMessage();
        await endpointInstance.SendLocal(myMessage)
        .ConfigureAwait(false);
    }
Exemple #23
0
        private static void InitLoggers(ServiceDescriptor d, bool enableCLILogging)
        {
            // TODO: Make logging levels configurable
            Level logLevel = Level.Debug;
            // TODO: Debug should not be printed to console by default. Otherwise commands like 'status' will be pollutted
            // This is a workaround till there is a better command line parsing, which will allow determining
            Level consoleLogLevel = Level.Info;
            Level eventLogLevel   = Level.Warn;

            // Legacy format from winsw-1.x: (DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message);
            PatternLayout pl = new PatternLayout {
                ConversionPattern = "%d %-5p - %m%n"
            };

            pl.ActivateOptions();

            List <IAppender> appenders = new List <IAppender>();

            // wrapper.log
            string wrapperLogPath = Path.Combine(d.LogDirectory, d.BaseName + ".wrapper.log");
            var    wrapperLog     = new FileAppender
            {
                AppendToFile   = true,
                File           = wrapperLogPath,
                ImmediateFlush = true,
                Name           = "Wrapper file log",
                Threshold      = logLevel,
                LockingModel   = new FileAppender.MinimalLock(),
                Layout         = pl
            };

            wrapperLog.ActivateOptions();
            appenders.Add(wrapperLog);

            // Also display logs in CLI if required
            if (enableCLILogging)
            {
                var consoleAppender = new ConsoleAppender
                {
                    Name      = "Wrapper console log",
                    Threshold = consoleLogLevel,
                    Layout    = pl,
                };
                consoleAppender.ActivateOptions();
                appenders.Add(consoleAppender);
            }

            // System log
            var systemEventLogger = new ServiceEventLogAppender
            {
                Name      = "System event log",
                Threshold = eventLogLevel,
                provider  = eventLogProvider
            };

            systemEventLogger.ActivateOptions();
            appenders.Add(systemEventLogger);

            BasicConfigurator.Configure(
#if NETCOREAPP
                LogManager.GetRepository(Assembly.GetExecutingAssembly()),
#endif
                appenders.ToArray());
        }
Exemple #24
0
        public static void Setup()
        {
            if (_blnIsInitialized)
            {
                return;
            }

            PatternLayout patternLayoutFull = new PatternLayout();

            patternLayoutFull.ConversionPattern = "%date  [%thread]  |%level|  |%class.%method() line: %line|  || %message %newline";
            patternLayoutFull.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();

            roller.Layout = patternLayoutFull;

            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            #region File logger

            roller.AppendToFile = true;

            roller.File = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                       string.Format(@"{0}\{1}.txt", Constants.APPLICATIONNAME, Constants.APPLICATIONNAME));
            roller.RollingStyle       = RollingFileAppender.RollingMode.Composite;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize    = "20MB";
            roller.StaticLogFileName  = true;
            roller.LockingModel       = new FileAppender.MinimalLock();
            roller.ActivateOptions();

            hierarchy.Root.AddAppender(roller);

            #endregion File logger

            //#region Windows Event Logger

            //var eventLoggerAppender = new EventLogAppender
            //{
            //    ApplicationName = Constants.APPLICATIONNAME,
            //    LogName = Constants.APPLICATIONNAME,
            //    Layout = patternLayout,
            //    Threshold = Level.Error
            //};
            //eventLoggerAppender.ActivateOptions();
            //hierarchy.Root.AddAppender(eventLoggerAppender);

            //#endregion Windows Event Logger

            if (Environment.UserInteractive)
            {
                // we write to console and capture it later to a WPF window
                //so, we only write the parts the end-user like to see
                var patternLayoutPartial = new PatternLayout();
                patternLayoutPartial.ConversionPattern = "%date  [%thread]  |%level|  || %message %newline";
                patternLayoutPartial.ActivateOptions();

                var consoleAppender = new ConsoleAppender
                {
                    Name      = Constants.APPLICATIONNAME,
                    Layout    = patternLayoutPartial,
                    Threshold = Level.All
                };
                consoleAppender.ActivateOptions();
                hierarchy.Root.AddAppender(consoleAppender);
            }

            hierarchy.Configured = true;

            _blnIsInitialized = true;
        }
//IBlazorApplicationBuilder
        //IComponentsApplicationBuilder
        public void Configure(IComponentsApplicationBuilder app)
        {
            bool result1 = WebRequest.RegisterPrefix("http://", new FakeRequestFactory());

            Console.WriteLine("webrequestmod " + result1);
            bool result2 = WebRequest.RegisterPrefix("https://", new FakeRequestFactory());

            Console.WriteLine("webrequestmod " + result2);

            app.AddComponent <App>("app");

            log4net.Repository.Hierarchy.Hierarchy hierarchy =
                (Hierarchy)log4net.LogManager.GetRepository(Assembly.GetAssembly(typeof(Startup)));

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            patternLayout.ActivateOptions();

            var cca = new ConsoleAppender();

            cca.Layout = patternLayout;
            cca.ActivateOptions();
            hierarchy.Root.AddAppender(cca);

            hierarchy.Root.Level = Level.Debug;
            hierarchy.Configured = true;

            log.Info("test");

            log.Info("Configure Done");

            //System.Net.WebRequest.get_InternalDefaultWebProxy

            //WebRequest.DefaultWebProxy = GlobalProxySelection.GetEmptyWebProxy();

            Directory.CreateDirectory(@"/home/web_user/Desktop");

            BinaryLog.onFlightMode += (firmware, modeno) =>
            {
                try
                {
                    if (firmware == "")
                    {
                        return(null);
                    }

                    var    modes       = Common.getModesList((Firmwares)Enum.Parse(typeof(Firmwares), firmware));
                    string currentmode = null;

                    foreach (var mode in modes)
                    {
                        if (mode.Key == modeno)
                        {
                            currentmode = mode.Value;
                            break;
                        }
                    }

                    return(currentmode);
                }
                catch
                {
                    return(null);
                }
            };

            CustomMessageBox.ShowEvent += (text, caption, buttons, icon, yestext, notext) =>
            {
                Console.WriteLine("CustomMessageBox " + caption + " " + text);


                return(CustomMessageBox.DialogResult.OK);
            };
        }
Exemple #26
0
    protected override void OnStart(string[] args)
    {
        #region logging
        PatternLayout layout = new PatternLayout
        {
            ConversionPattern = "%d %-5p %c - %m%n"
        };
        layout.ActivateOptions();
        ConsoleAppender appender = new ConsoleAppender
        {
            Layout    = layout,
            Threshold = Level.Info
        };
        appender.ActivateOptions();

        BasicConfigurator.Configure(appender);

        LogManager.Use <Log4NetFactory>();
        #endregion

        #region create-config
        BusConfiguration busConfiguration = new BusConfiguration();
        #endregion

        #region endpoint-name
        busConfiguration.EndpointName("Sample.FirstEndpoint");
        #endregion

        #region container
        ContainerBuilder builder = new ContainerBuilder();
        //configure your custom services
        //builder.RegisterInstance(new MyService());
        IContainer container = builder.Build();
        busConfiguration.UseContainer <AutofacBuilder>(c => c.ExistingLifetimeScope(container));
        #endregion

        #region serialization
        busConfiguration.UseSerialization <JsonSerializer>();
        #endregion

        #region transport
        busConfiguration.UseTransport <MsmqTransport>();
        #endregion

        #region sagas
        //Not required since Sagas are enabled by default in Version 5
        #endregion

        #region persistence
        busConfiguration.UsePersistence <InMemoryPersistence, StorageType.Sagas>();
        busConfiguration.UsePersistence <InMemoryPersistence, StorageType.Subscriptions>();
        busConfiguration.UsePersistence <InMemoryPersistence, StorageType.Timeouts>();
        #endregion

        #region critical-errors
        busConfiguration.DefineCriticalErrorAction((errorMessage, exception) =>
        {
            // Log the critical error
            logger.Fatal(string.Format("CRITICAL: {0}", errorMessage), exception);

            // Kill the process on a critical error
            Environment.FailFast(string.Format("The following critical error was encountered by NServiceBus:\n{0}\nNServiceBus is shutting down.", errorMessage), exception);
        });
        #endregion

        #region start-bus
        busConfiguration.EnableInstallers();
        bus = Bus.Create(busConfiguration).Start();
        #endregion
    }
Exemple #27
0
    protected override void OnStart(string[] args)
    {
        #region logging
        PatternLayout layout = new PatternLayout
        {
            ConversionPattern = "%d %-5p %c - %m%n"
        };
        layout.ActivateOptions();
        ConsoleAppender appender = new ConsoleAppender
        {
            Layout    = layout,
            Threshold = Level.Info
        };
        appender.ActivateOptions();

        BasicConfigurator.Configure(appender);

        SetLoggingLibrary.Log4Net();
        #endregion

        #region create-config
        Configure configure = Configure.With();
        #endregion
        #region endpoint-name
        configure.DefineEndpointName("Samples.FirstEndpoint");
        #endregion

        #region container
        ContainerBuilder builder = new ContainerBuilder();
        //configure your custom services
        //builder.RegisterInstance(new MyService());
        IContainer container = builder.Build();
        configure.AutofacBuilder(container);
        #endregion

        #region serialization
        Configure.Serialization.Json();
        #endregion

        #region transport
        configure.UseTransport <Msmq>();
        #endregion

        #region sagas
        Configure.Features.Enable <Sagas>();
        #endregion

        #region persistence
        configure.InMemorySagaPersister();
        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();
        #endregion

        #region critical-errors
        Configure.Instance.DefineCriticalErrorAction((errorMessage, exception) =>
        {
            // Log the critical error
            logger.Fatal(string.Format("CRITICAL: {0}", errorMessage), exception);

            // Kill the process on a critical error
            Environment.FailFast(string.Format("The following critical error was encountered by NServiceBus:\n{0}\nNServiceBus is shutting down.", errorMessage), exception);
        });
        #endregion

        #region start-bus
        bus = configure.UnicastBus()
              .CreateBus()
              .Start(() => configure.ForInstallationOn <Windows>().Install());
        #endregion
    }
Exemple #28
0
        public static void Run(string[] argsArray, IServiceConfig?config = null)
        {
            bool inConsoleMode = argsArray.Length > 0;

            config ??= LoadConfigAndInitLoggers(inConsoleMode);

            if (!inConsoleMode)
            {
                Log.Debug("Starting WinSW in service mode");
                using var service = new WrapperService(config);
                try
                {
                    ServiceBase.Run(service);
                }
                catch
                {
                    // handled in OnStart
                }

                return;
            }

            Log.Debug("Starting WinSW in console mode");

            if (argsArray.Length == 0)
            {
                PrintHelp();
                return;
            }

            var args = new List <string>(Array.AsReadOnly(argsArray));

            if (args[0] == "/redirect")
            {
                var f = new FileStream(args[1], FileMode.Create);
                var w = new StreamWriter(f)
                {
                    AutoFlush = true
                };
                Console.SetOut(w);
                Console.SetError(w);

                var handle = f.SafeFileHandle;
                _ = Kernel32.SetStdHandle(-11, handle); // set stdout
                _ = Kernel32.SetStdHandle(-12, handle); // set stder

                args = args.GetRange(2, args.Count - 2);
            }

            bool elevated;

            if (args[0] == "/elevated")
            {
                elevated = true;

                _ = ConsoleApis.FreeConsole();
                _ = ConsoleApis.AttachConsole(ConsoleApis.ATTACH_PARENT_PROCESS);

#if VNEXT
                string stdinName = args[1];
                if (stdinName != NoPipe)
                {
                    var stdin = new NamedPipeClientStream(".", stdinName, PipeDirection.In, PipeOptions.Asynchronous);
                    stdin.Connect();
                    Console.SetIn(new StreamReader(stdin));
                }

                string stdoutName = args[2];
                if (stdoutName != NoPipe)
                {
                    var stdout = new NamedPipeClientStream(".", stdoutName, PipeDirection.Out, PipeOptions.Asynchronous);
                    stdout.Connect();
                    Console.SetOut(new StreamWriter(stdout)
                    {
                        AutoFlush = true
                    });
                }

                string stderrName = args[3];
                if (stderrName != NoPipe)
                {
                    var stderr = new NamedPipeClientStream(".", stderrName, PipeDirection.Out, PipeOptions.Asynchronous);
                    stderr.Connect();
                    Console.SetError(new StreamWriter(stderr)
                    {
                        AutoFlush = true
                    });
                }

                args = args.GetRange(4, args.Count - 4);
#else
                args = args.GetRange(1, args.Count - 1);
#endif
            }
            else if (Environment.OSVersion.Version.Major == 5)
            {
                // Windows XP
                elevated = true;
            }
            else
            {
                elevated = IsProcessElevated();
            }

            switch (args[0].ToLower())
            {
            case "install":
                Install();
                return;

            case "uninstall":
                Uninstall();
                return;

            case "start":
                Start();
                return;

            case "stop":
                Stop(true);
                return;

            case "stopwait":
                Stop(false);
                return;

            case "restart":
                Restart();
                return;

            case "restart!":
                RestartSelf();
                return;

            case "status":
                Status();
                return;

            case "test":
                Test();
                return;

            case "testwait":
                TestWait();
                return;

            case "help":
            case "--help":
            case "-h":
            case "-?":
            case "/?":
                PrintHelp();
                return;

            case "version":
                PrintVersion();
                return;

            default:
                Console.WriteLine("Unknown command: " + args[0]);
                PrintAvailableCommands();
                throw new Exception("Unknown command: " + args[0]);
            }

            void Install()
            {
                if (!elevated)
                {
                    Elevate();
                    return;
                }

                Log.Info($"Installing service '{Format(config)}'...");

                using var scm = ServiceManager.Open(ServiceManagerAccess.CreateService);

                if (scm.ServiceExists(config.Name))
                {
                    Log.Error($"A service with ID '{config.Name}' already exists.");
                    Throw.Command.Win32Exception(Errors.ERROR_SERVICE_EXISTS, "Failed to install the service.");
                }

                string?username = null;
                string?password = null;
                bool   allowServiceLogonRight = false;

                if (args.Count > 1 && args[1] == "/p")
                {
                    Credentials.PromptForCredentialsConsole(ref username, ref password);
                    Console.Write("Set Account rights to allow log on as a service (y/n)?: ");
                    var keypressed = Console.ReadKey();
                    Console.WriteLine();
                    if (keypressed.Key == ConsoleKey.Y)
                    {
                        allowServiceLogonRight = true;
                    }
                }
                else
                {
                    if (config.ServiceAccount.HasServiceAccount())
                    {
                        username = config.ServiceAccount.FullUser;
                        password = config.ServiceAccount.Password;
                        allowServiceLogonRight = config.ServiceAccount.AllowServiceLogonRight;
                    }
                }

                if (allowServiceLogonRight)
                {
                    Security.AddServiceLogonRight(config.ServiceAccount.Domain !, config.ServiceAccount.User !);
                }

                using var sc = scm.CreateService(
                          config.Name,
                          config.DisplayName,
                          config.Interactive,
                          config.StartMode,
                          $"\"{config.ExecutablePath}\"",
                          config.ServiceDependencies,
                          username,
                          password);

                string description = config.Description;

                if (description.Length != 0)
                {
                    sc.SetDescription(description);
                }

                var actions = config.FailureActions;

                if (actions.Length > 0)
                {
                    sc.SetFailureActions(config.ResetFailureAfter, actions);
                }

                bool isDelayedAutoStart = config.StartMode == ServiceStartMode.Automatic && config.DelayedAutoStart;

                if (isDelayedAutoStart)
                {
                    sc.SetDelayedAutoStart(true);
                }

                string?securityDescriptor = config.SecurityDescriptor;

                if (securityDescriptor != null)
                {
                    // throws ArgumentException
                    sc.SetSecurityDescriptor(new RawSecurityDescriptor(securityDescriptor));
                }

                string eventLogSource = config.Name;

                if (!EventLog.SourceExists(eventLogSource))
                {
                    EventLog.CreateEventSource(eventLogSource, "Application");
                }

                Log.Info($"Service '{Format(config)}' was installed successfully.");
            }

            void Uninstall()
            {
                if (!elevated)
                {
                    Elevate();
                    return;
                }

                Log.Info($"Uninstalling service '{Format(config)}'...");

                using var scm = ServiceManager.Open(ServiceManagerAccess.Connect);
                try
                {
                    using var sc = scm.OpenService(config.Name);

                    if (sc.Status != ServiceControllerStatus.Stopped)
                    {
                        // We could fail the opeartion here, but it would be an incompatible change.
                        // So it is just a warning
                        Log.Warn($"Service '{Format(config)}' is started. It may be impossible to uninstall it.");
                    }

                    sc.Delete();

                    Log.Info($"Service '{Format(config)}' was uninstalled successfully.");
                }
                catch (CommandException e) when(e.InnerException is Win32Exception inner)
                {
                    switch (inner.NativeErrorCode)
                    {
                    case Errors.ERROR_SERVICE_DOES_NOT_EXIST:
                        Log.Warn($"Service '{Format(config)}' does not exist.");
                        break;     // there's no such service, so consider it already uninstalled

                    case Errors.ERROR_SERVICE_MARKED_FOR_DELETE:
                        Log.Error(e.Message);

                        // TODO: change the default behavior to Error?
                        break;     // it's already uninstalled, so consider it a success

                    default:
                        Throw.Command.Exception("Failed to uninstall the service.", inner);
                        break;
                    }
                }
            }

            void Start()
            {
                if (!elevated)
                {
                    Elevate();
                    return;
                }

                using var svc = new ServiceController(config.Name);

                try
                {
                    Log.Info($"Starting service '{Format(svc)}'...");
                    svc.Start();

                    Log.Info($"Service '{Format(svc)}' started successfully.");
                }
                catch (InvalidOperationException e)
                    when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_DOES_NOT_EXIST)
                    {
                        Throw.Command.Exception(inner);
                    }
                catch (InvalidOperationException e)
                    when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_ALREADY_RUNNING)
                    {
                        Log.Info($"Service '{Format(svc)}' has already started.");
                    }
            }

            void Stop(bool noWait)
            {
                if (!elevated)
                {
                    Elevate();
                    return;
                }

                using var svc = new ServiceController(config.Name);

                try
                {
                    Log.Info($"Stopping service '{Format(svc)}'...");
                    svc.Stop();

                    if (!noWait)
                    {
                        try
                        {
                            WaitForStatus(svc, ServiceControllerStatus.Stopped, ServiceControllerStatus.StopPending);
                        }
                        catch (TimeoutException)
                        {
                            Throw.Command.Exception("Failed to stop the service.");
                        }
                    }

                    Log.Info($"Service '{Format(svc)}' stopped successfully.");
                }
                catch (InvalidOperationException e)
                    when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_DOES_NOT_EXIST)
                    {
                        Throw.Command.Exception(inner);
                    }
                catch (InvalidOperationException e)
                    when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_NOT_ACTIVE)
                    {
                        Log.Info($"Service '{Format(svc)}' has already stopped.");
                    }
            }

            void Restart()
            {
                if (!elevated)
                {
                    Elevate();
                    return;
                }


                using var svc = new ServiceController(config.Name);

                List <ServiceController>?startedDependentServices = null;

                try
                {
                    if (HasAnyStartedDependentService(svc))
                    {
                        startedDependentServices = new();
                        foreach (var service in svc.DependentServices)
                        {
                            if (service.Status != ServiceControllerStatus.Stopped)
                            {
                                startedDependentServices.Add(service);
                            }
                        }
                    }

                    Log.Info($"Stopping service '{Format(svc)}'...");
                    svc.Stop();

                    try
                    {
                        WaitForStatus(svc, ServiceControllerStatus.Stopped, ServiceControllerStatus.StopPending);
                    }
                    catch (TimeoutException)
                    {
                        Throw.Command.Exception("Failed to stop the service.");
                    }
                }
                catch (InvalidOperationException e)
                    when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_DOES_NOT_EXIST)
                    {
                        Throw.Command.Exception(inner);
                    }
                catch (InvalidOperationException e)
                    when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_NOT_ACTIVE)
                    {
                    }

                Log.Info($"Starting service '{Format(svc)}'...");
                svc.Start();

                try
                {
                    WaitForStatus(svc, ServiceControllerStatus.Running, ServiceControllerStatus.StartPending);
                }
                catch (TimeoutException)
                {
                    Throw.Command.Exception("Failed to start the service.");
                }

                if (startedDependentServices != null)
                {
                    foreach (var service in startedDependentServices)
                    {
                        if (service.Status == ServiceControllerStatus.Stopped)
                        {
                            Log.Info($"Starting service '{Format(service)}'...");
                            service.Start();
                        }
                    }
                }

                Log.Info($"Service '{Format(svc)}' restarted successfully.");
            }

            void RestartSelf()
            {
                if (!elevated)
                {
                    Throw.Command.Win32Exception(Errors.ERROR_ACCESS_DENIED);
                }

                Log.Info("Restarting the service with id '" + config.Name + "'");

                // run restart from another process group. see README.md for why this is useful.
                if (!ProcessApis.CreateProcess(
                        null,
                        config.ExecutablePath + " restart",
                        IntPtr.Zero,
                        IntPtr.Zero,
                        false,
                        ProcessApis.CREATE_NEW_PROCESS_GROUP,
                        IntPtr.Zero,
                        null,
                        default,
                        out var processInfo))
                {
                    Throw.Command.Win32Exception("Failed to invoke restart.");
                }

                _ = HandleApis.CloseHandle(processInfo.ProcessHandle);
                _ = HandleApis.CloseHandle(processInfo.ThreadHandle);
            }

            void Status()
            {
                using var svc = new ServiceController(config.Name);
                try
                {
                    Console.WriteLine(svc.Status != ServiceControllerStatus.Stopped ? "Started" : "Stopped");
                }
                catch (InvalidOperationException e)
                    when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_DOES_NOT_EXIST)
                    {
                        Console.WriteLine("NonExistent");
                    }
            }

            void Test()
            {
                if (!elevated)
                {
                    Elevate();
                    return;
                }

                var wsvc = new WrapperService(config);

                wsvc.RaiseOnStart(args.ToArray());
                Thread.Sleep(1000);
                wsvc.RaiseOnStop();
            }

            void TestWait()
            {
                if (!elevated)
                {
                    Elevate();
                    return;
                }

                var wsvc = new WrapperService(config);

                wsvc.RaiseOnStart(args.ToArray());
                Console.WriteLine("Press any key to stop the service...");
                _ = Console.Read();
                wsvc.RaiseOnStop();
            }

            // [DoesNotReturn]
            void Elevate()
            {
#if VNEXT
                string?stdinName  = Console.IsInputRedirected ? Guid.NewGuid().ToString() : null;
                string?stdoutName = Console.IsOutputRedirected ? Guid.NewGuid().ToString() : null;
                string?stderrName = Console.IsErrorRedirected ? Guid.NewGuid().ToString() : null;
#endif

                string exe         = Environment.GetCommandLineArgs()[0];
                string commandLine = Environment.CommandLine;
                string arguments   = "/elevated" +
#if VNEXT
                                     " " + (stdinName ?? NoPipe) +
                                     " " + (stdoutName ?? NoPipe) +
                                     " " + (stderrName ?? NoPipe) +
#endif
                                     commandLine.Remove(commandLine.IndexOf(exe), exe.Length).TrimStart('"');

                var startInfo = new ProcessStartInfo
                {
                    UseShellExecute = true,
                    Verb            = "runas",
                    FileName        = ExecutablePath,
                    Arguments       = arguments,
                    WindowStyle     = ProcessWindowStyle.Hidden,
                };

                try
                {
                    using var elevated = Process.Start(startInfo) !;

#if VNEXT
                    if (stdinName != null)
                    {
                        var stdin = new NamedPipeServerStream(stdinName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
                        stdin.WaitForConnectionAsync().ContinueWith(_ => Console.OpenStandardInput().CopyToAsync(stdin));
                    }

                    if (stdoutName != null)
                    {
                        var stdout = new NamedPipeServerStream(stdoutName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
                        stdout.WaitForConnectionAsync().ContinueWith(_ => stdout.CopyToAsync(Console.OpenStandardOutput()));
                    }

                    if (stderrName != null)
                    {
                        var stderr = new NamedPipeServerStream(stderrName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
                        stderr.WaitForConnectionAsync().ContinueWith(_ => stderr.CopyToAsync(Console.OpenStandardError()));
                    }
#endif

                    elevated.WaitForExit();
                    Environment.Exit(elevated.ExitCode);
                }
                catch (Win32Exception e) when(e.NativeErrorCode == Errors.ERROR_CANCELLED)
                {
                    Log.Fatal(e.Message);
                    Environment.Exit(e.ErrorCode);
                }
            }
        }

        private static IServiceConfig LoadConfigAndInitLoggers(bool inConsoleMode)
        {
            // TODO: Make logging levels configurable
            var fileLogLevel = Level.Debug;

            // TODO: Debug should not be printed to console by default. Otherwise commands like 'status' will be pollutted
            // This is a workaround till there is a better command line parsing, which will allow determining
            var consoleLogLevel = Level.Info;
            var eventLogLevel   = Level.Warn;

            var layout = new PatternLayout {
                ConversionPattern = "%d %-5p - %m%n"
            };

            layout.ActivateOptions();

            var repository = LogManager.GetRepository(Assembly.GetExecutingAssembly());

            if (inConsoleMode)
            {
                var consoleAppender = new ConsoleAppender
                {
                    Name      = "Wrapper console log",
                    Threshold = consoleLogLevel,
                    Layout    = layout,
                };
                consoleAppender.ActivateOptions();

                BasicConfigurator.Configure(repository, consoleAppender);
            }
            else
            {
                var eventLogAppender = new ServiceEventLogAppender(WrapperService.eventLogProvider)
                {
                    Name      = "Wrapper event log",
                    Threshold = eventLogLevel,
                };
                eventLogAppender.ActivateOptions();

                BasicConfigurator.Configure(repository, eventLogAppender);
            }

            string executablePath = ExecutablePath;
            string directory      = Path.GetDirectoryName(executablePath) !;
            string baseName       = Path.GetFileNameWithoutExtension(executablePath);

            IServiceConfig config =
                File.Exists(Path.Combine(directory, baseName + ".xml")) ? new XmlServiceConfig(baseName, directory) :
                File.Exists(Path.Combine(directory, baseName + ".yml")) ? new YamlServiceConfig(baseName, directory) :
                throw new FileNotFoundException($"Unable to locate {baseName}.[xml|yml] file within executable directory");

            // .wrapper.log
            string wrapperLogPath = Path.Combine(config.LogDirectory, config.BaseName + ".wrapper.log");
            var    fileAppender   = new FileAppender
            {
                AppendToFile   = true,
                File           = wrapperLogPath,
                ImmediateFlush = true,
                Name           = "Wrapper file log",
                Threshold      = fileLogLevel,
                LockingModel   = new FileAppender.MinimalLock(),
                Layout         = layout,
            };

            fileAppender.ActivateOptions();

            BasicConfigurator.Configure(repository, fileAppender);

            return(config);
        }

        internal static unsafe bool IsProcessElevated()
    async Task AsyncOnStart()
    {
        #region logging

        PatternLayout layout = new PatternLayout
        {
            ConversionPattern = "%d %-5p %c - %m%n"
        };
        layout.ActivateOptions();
        ConsoleAppender appender = new ConsoleAppender
        {
            Layout    = layout,
            Threshold = Level.Info
        };
        appender.ActivateOptions();

        BasicConfigurator.Configure(appender);

        LogManager.Use <Log4NetFactory>();

        #endregion

        #region create-config

        EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.FirstEndpoint");

        #endregion

        #region container

        ContainerBuilder builder = new ContainerBuilder();
        //configure custom services
        //builder.RegisterInstance(new MyService());
        IContainer container = builder.Build();
        endpointConfiguration.UseContainer <AutofacBuilder>(c => c.ExistingLifetimeScope(container));

        #endregion

        #region serialization

        endpointConfiguration.UseSerialization <JsonSerializer>();

        #endregion
        #region error
        endpointConfiguration.SendFailedMessagesTo("error");
        #endregion

        #region transport

        endpointConfiguration.UseTransport <MsmqTransport>();

        #endregion

        #region persistence

        endpointConfiguration.UsePersistence <InMemoryPersistence, StorageType.Sagas>();
        endpointConfiguration.UsePersistence <InMemoryPersistence, StorageType.Subscriptions>();
        endpointConfiguration.UsePersistence <InMemoryPersistence, StorageType.Timeouts>();

        #endregion

        #region critical-errors
        endpointConfiguration.DefineCriticalErrorAction(async context =>
        {
            // Log the critical error
            logger.Fatal($"CRITICAL: {context.Error}", context.Exception);

            await context.Stop();

            // Kill the process on a critical error
            string output = $"The following critical error was encountered by NServiceBus:\n{context.Error}\nNServiceBus is shutting down.";
            Environment.FailFast(output, context.Exception);
        });

        #endregion

        #region start-bus

        endpointConfiguration.EnableInstallers();
        endpoint = await Endpoint.Start(endpointConfiguration);

        #endregion


        await endpoint.SendLocal(new MyMessage());
    }
    protected override void OnStart(string[] args)
    {
        #region logging
        PatternLayout layout = new PatternLayout
        {
            ConversionPattern = "%d %-5p %c - %m%n"
        };
        layout.ActivateOptions();
        ConsoleAppender appender = new ConsoleAppender
        {
            Layout    = layout,
            Threshold = Level.Info
        };
        appender.ActivateOptions();

        BasicConfigurator.Configure(appender);

        SetLoggingLibrary.Log4Net();
        #endregion

        #region create-config
        Configure configure = Configure.With();
        configure.DefineEndpointName("Samples.FirstEndpoint");
        #endregion

        #region container
        ContainerBuilder builder = new ContainerBuilder();
        //configure custom services
        //builder.RegisterInstance(new MyService());
        IContainer container = builder.Build();
        configure.AutofacBuilder(container);
        #endregion

        #region serialization
        configure.JsonSerializer();
        #endregion

        #region transport
        configure.MsmqTransport();
        #endregion

        #region sagas
        configure.Sagas();
        #endregion

        #region persistence
        configure.InMemorySagaPersister();
        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();
        #endregion

        #region critical-errors
        Configure.Instance.DefineCriticalErrorAction(() =>
        {
            //Write log entry in version 3 since this is not done by default.
            logger.Fatal("CRITICAL Error");

            // Kill the process on a critical error
            string output = "Critical error was encountered by NServiceBus:\nNServiceBus is shutting down.";
            Environment.FailFast(output);
        });
        #endregion

        #region start-bus
        bus = configure.UnicastBus()
              .CreateBus()
              .Start(() => configure.ForInstallationOn <Windows>().Install());
        #endregion

        bus.SendLocal(new MyMessage());
    }