Пример #1
0
    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();

        var executingAssembly = Assembly.GetExecutingAssembly();
        var repository        = log4net.LogManager.GetRepository(executingAssembly);
        BasicConfigurator.Configure(repository, 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);
    }
 private void pattern()
 {
     layout = new PatternLayout("%newline %date{MMM/dd/yyyy HH:mm:ss,fff} [%-5level] [Thread:%thread] %logger %newline %message %newline");
 }
Пример #3
0
 public TestOutputAppender(ITestOutputHelper xunitTestOutputHelper)
 {
     _xunitTestOutputHelper = xunitTestOutputHelper;
     Name   = "TestOutputAppender";
     Layout = new PatternLayout("%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n");
 }
Пример #4
0
        public static bool WriteLog(object message, Exception ex = null, Level level = Level.Info)
        {
            lock (logLock)
            {
                try
                {
                    if (message == null || string.IsNullOrWhiteSpace(message.ToString()))
                    {
                        return(false);                                                                   //不写空日志
                    }
                    if (logger == null)
                    {
                        PatternLayout patternLayout = new PatternLayout();
                        patternLayout.ConversionPattern = LOG_PATTERN;
                        patternLayout.ActivateOptions();

                        TraceAppender tracer = new TraceAppender();
                        tracer.Layout = patternLayout;
                        tracer.ActivateOptions();

                        RollingFileAppender roller = new RollingFileAppender();
                        roller.Layout             = patternLayout;
                        roller.AppendToFile       = true;
                        roller.File               = "Log/";
                        roller.StaticLogFileName  = false;
                        roller.DatePattern        = "yyyyMMdd.LOG";
                        roller.RollingStyle       = RollingFileAppender.RollingMode.Date;
                        roller.MaximumFileSize    = "10MB";
                        roller.MaxSizeRollBackups = 10;
                        roller.ImmediateFlush     = true;
                        roller.Encoding           = Encoding.UTF8;
                        roller.LockingModel       = new FileAppender.MinimalLock();
                        roller.ActivateOptions();

                        Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
                        hierarchy.Name = "log";
                        hierarchy.Root.AddAppender(tracer);
                        hierarchy.Root.AddAppender(roller);
                        hierarchy.Root.Level = log4net.Core.Level.All;
                        hierarchy.Configured = true;

                        logger = LogManager.GetLogger("log");
                    }

                    if (ex == null)
                    {
                        switch (level)
                        {
                        case Level.Debug:
                            logger.Debug(message);
                            break;

                        case Level.Error:
                            logger.Error(message);
                            break;

                        case Level.Fatal:
                            logger.Fatal(message);
                            break;

                        case Level.Info:
                            logger.Info(message);
                            break;

                        case Level.Warn:
                            logger.Warn(message);
                            break;
                        }
                    }
                    else
                    {
                        switch (level)
                        {
                        case Level.Debug:
                            logger.Debug(message, ex);
                            break;

                        case Level.Error:
                            logger.Error(message, ex);
                            break;

                        case Level.Fatal:
                            logger.Fatal(message, ex);
                            break;

                        case Level.Info:
                            logger.Info(message, ex);
                            break;

                        case Level.Warn:
                            logger.Warn(message, ex);
                            break;
                        }
                    }
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
        /// <summary>
        /// Parse a single member arrangement
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public IArrangement ParseArangement(string str)
        {
            var match = s_singleMatcher.Match(str);

            var name   = match.Groups["Name"].Value;
            var op     = match.Groups["Op"].Value;
            var value  = match.Groups["Value"].Value;
            var option = match.Groups["Option"].Value;
            var convs  = GetConverterContext().Get();

            if (!match.Success)
            {
                name  = String.Empty;
                op    = "|";
                value = str;
            }

            name = s_nameClean.Replace(name, Clean);

            if (op == String.Empty)
            {
                if (value == String.Empty)
                {
                    op    = ":";
                    value = name;
                }
                else
                {
                    op = "|";
                }
            }

            IArrangement ar;

            switch (op)
            {
            case "!":
                // custom arrangements, removals, defaults or swaps
                switch (name)
                {
                case "CLEAR":
                case "REMOVE":
                    // removals
                    ar = new RemovalArrangement(value);
                    break;

                case "DEFAULT":
                    // defaults
                    ar = new DefaultArrangement(value);
                    break;

                default:
                    // custom arrangements
                    var type = Type.GetType(name, false);
                    if (type == null)
                    {
                        throw new Exception(String.Format("Arrangement type not found: {0}", name));
                    }
                    var arrangement = Activator.CreateInstance(type) as IArrangement;
                    if (arrangement == null)
                    {
                        throw new Exception(String.Format("Arrangement type is not IArrangement: {0}", type));
                    }
                    arrangement.SetOption(value);
                    ar = arrangement;
                    break;
                }
                break;

            case ":":
                // just rename members
                var cons =
                    ar = new Member()
                {
                    Name       = name,
                    Converters = convs,
                    Option     = new Member()
                    {
                        Name       = value,
                        Converters = convs
                    }
                };
                break;

            case "|":
                // run a nested pattern layout
                value = s_brackClean.Replace(value, Brackets);
                value = s_nameClean.Replace(value, Clean);
                var pl = new PatternLayout(value);
                if (convs != null)
                {
                    foreach (var conv in convs)
                    {
                        pl.AddConverter(conv);
                    }
                }
                ar = new Member()
                {
                    Name       = name,
                    Converters = convs,
                    Option     = pl
                };
                break;

            case "%":
                // run a nested pattern layout
                var pl2 = new PatternLayout(string.Format("%{0}{{{1}}}", value, option));
                if (convs != null)
                {
                    foreach (var conv in convs)
                    {
                        pl2.AddConverter(conv);
                    }
                }
                ar = new Member()
                {
                    Name       = name,
                    Converters = convs,
                    Option     = pl2
                };
                break;

            case "=":
                // a member with an option
                ar = new Member()
                {
                    Name       = name,
                    Converters = convs,
                    Option     = value
                };
                break;

            default:
                throw new Exception(String.Format("Unknown arrangement: '{0}{1}'", name, op));
            }

            if (ar is IOptionHandler)
            {
                ((IOptionHandler)ar).ActivateOptions();
            }

            return(ar);
        }
        /// <summary>
        ///   Adds a file appender to all current loggers. Only runs one time.
        /// </summary>
        /// <param name="outputDirectory">The output directory.</param>
        /// <param name="excludeLoggerNames">Loggers, such as a trace logger, to exclude from file appender.</param>
        private static void set_file_appender(string outputDirectory, params string[] excludeLoggerNames)
        {
            if (excludeLoggerNames == null)
            {
                excludeLoggerNames = new string[] {}
            }
            ;

            if (!_alreadyConfiguredFileAppender)
            {
                _alreadyConfiguredFileAppender = true;

                var layout = new PatternLayout
                {
                    ConversionPattern = "%date %property{pid} [%-5level] - %message%newline"
                };
                layout.ActivateOptions();

                var app = new RollingFileAppender
                {
                    Name                         = "{0}.changes.log.appender".format_with(ApplicationParameters.Name),
                    File                         = Path.Combine(Path.GetFullPath(outputDirectory), ApplicationParameters.LoggingFile),
                    Layout                       = layout,
                    AppendToFile                 = true,
                    RollingStyle                 = RollingFileAppender.RollingMode.Size,
                    MaxFileSize                  = 1024 * 1024 * 10,
                    MaxSizeRollBackups           = 50,
                    LockingModel                 = new FileAppender.MinimalLock(),
                    PreserveLogFileNameExtension = true,
                };
                app.ActivateOptions();

                var infoOnlyAppender = new RollingFileAppender
                {
                    Name                         = _summaryLogAppenderName,
                    File                         = Path.Combine(Path.GetFullPath(outputDirectory), ApplicationParameters.LoggingSummaryFile),
                    Layout                       = layout,
                    AppendToFile                 = true,
                    RollingStyle                 = RollingFileAppender.RollingMode.Size,
                    MaxFileSize                  = 1024 * 1024 * 10,
                    MaxSizeRollBackups           = 50,
                    LockingModel                 = new FileAppender.MinimalLock(),
                    PreserveLogFileNameExtension = true,
                };
                infoOnlyAppender.AddFilter(new LevelRangeFilter {
                    LevelMin = Level.Info, LevelMax = Level.Fatal
                });
                infoOnlyAppender.ActivateOptions();

                ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetCallingAssembly().UnderlyingType);
                foreach (ILogger log in logRepository.GetCurrentLoggers().Where(l => excludeLoggerNames.All(name => !l.Name.is_equal_to(name))).or_empty_list_if_null())
                {
                    var logger = log as Logger;
                    if (logger != null)
                    {
                        logger.AddAppender(app);
                        logger.AddAppender(infoOnlyAppender);
                    }
                }
            }
        }
Пример #7
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());
        }
Пример #8
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.Instance.ForInstallationOn <Windows>().Install());
        #endregion
    }
Пример #9
0
        public void SetupLogNetLogger(string loggerName, string logLocation, SeverityLevel sl)
        {
            ILog log    = LogManager.GetLogger(loggerName);
            var  logger = (Logger)log.Logger;

            //Add the default log appender if none exist
            if (logger.Appenders.Count != 0)
            {
                return;
            }

            //If the directory doesn't exist then create it
            if (!Directory.Exists(logLocation))
            {
                Directory.CreateDirectory(logLocation);
            }

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

            //Create the rolling file appender
            var appender = new RollingFileAppender
            {
                Name              = "RollingFileAppener" + loggerName,
                AppendToFile      = true,
                File              = logLocation,
                Layout            = patternLayout,
                MaximumFileSize   = "100MB",
                RollingStyle      = RollingFileAppender.RollingMode.Date,
                DatePattern       = "'" + loggerName + "-'yyyy-MM-dd'.log'",
                StaticLogFileName = false,
                ImmediateFlush    = true,
            };

            switch (sl)
            {
            case SeverityLevel.Debug:
                appender.Threshold = Level.Debug;
                break;

            case SeverityLevel.Warn:
                appender.Threshold = Level.Warn;
                break;

            case SeverityLevel.Info:
                appender.Threshold = Level.Info;
                break;

            case SeverityLevel.Error:
                appender.Threshold = Level.Error;
                break;

            case SeverityLevel.Fatal:
                appender.Threshold = Level.Fatal;
                break;

            default:
                appender.Threshold = Level.Debug;
                break;
            }

            //Configure the layout of the trace message write
            var layout = new PatternLayout()
            {
                ConversionPattern = "%date [%thread] %-5level %message%newline"
            };

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

            //Let log4net configure itself based on the values provided
            appender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(appender);
            logger.Additivity = false;

            logger.AddAppender(appender);

            //if(LoggerInstanceConstants.MainLoggerInstance == loggerName)
            //    ((log4net.Repository.Hierarchy.Hierarchy)logger.Repository).Root.AddAppender(appender);
        }
Пример #10
0
        //void UseFileCofnig(ILoggerRepository rep)
        //{
        //    var type = MethodBase.GetCurrentMethod().DeclaringType;
        //    if (type != null)
        //    {
        //        var ns = type.Namespace;
        //        Assembly assembly = Assembly.GetExecutingAssembly();
        //        string resourceName = ns + ".log4net.config";
        //        Stream stream = assembly.GetManifestResourceStream(resourceName);
        //        XmlConfigurator.Configure(rep, stream);
        //    }
        //}

        //void UseCodeConfig(Hierarchy repository, string type)
        void UseCodeConfig(Hierarchy repository, LogLevel logLevel)
        {
            if (_options.EnableFileLog && (_options.FileLogLevel & logLevel) == logLevel)
            {
                PatternLayout layout = new PatternLayout
                {
                    ConversionPattern = "%date{yyyy-MM-dd HH:mm:ss.fff} %-5p %m%n"
                };
                layout.ActivateOptions();

                RollingFileAppender roller = new RollingFileAppender
                {
                    AppendToFile = false
                };
                var path = _options.EnableFileLog ? _options.FileLogPath : "log";
                roller.File = $@"{path}\{logLevel.ToString().ToLower()}\";
                roller.PreserveLogFileNameExtension = true;
                roller.StaticLogFileName            = false;
                roller.MaxSizeRollBackups           = 0;
                roller.DatePattern  = $@"yyyyMMdd"".log""";
                roller.RollingStyle = RollingFileAppender.RollingMode.Date;
                roller.Layout       = layout;
                roller.MaxFileSize  = 10000000;
                switch (logLevel)
                {
                case LogLevel.Debug:
                    roller.Threshold = Level.Debug;
                    break;

                case LogLevel.Info:
                    roller.Threshold = Level.Info;
                    break;

                case LogLevel.Warn:
                    roller.Threshold = Level.Warn;
                    break;

                case LogLevel.Error:
                    roller.Threshold = Level.Error;
                    break;
                }
                roller.ActivateOptions();
                repository.Root.AddAppender(roller);
            }

            if (_options.EnableConsoleLog && (_options.ConsoleLogLevel & logLevel) == logLevel)
            {
                //ManagedColoredConsoleAppender managedColoredConsoleAppender = new
                ManagedColoredConsoleAppender console = new ManagedColoredConsoleAppender();
                PatternLayout layoutConsole           = new PatternLayout
                {
                    ConversionPattern = "%n%date{yyyy-MM-dd HH:mm:ss.fff} %-5level %m",
                };
                switch (logLevel)
                {
                case LogLevel.Debug:
                    console.Threshold = Level.Debug;
                    break;

                case LogLevel.Info:
                    console.Threshold = Level.Info;
                    break;

                case LogLevel.Warn:
                    console.Threshold = Level.Warn;
                    break;

                case LogLevel.Error:
                    console.Threshold = Level.Error;
                    break;
                }
                console.AddMapping(
                    new ManagedColoredConsoleAppender.LevelColors {
                    Level = Level.Error, ForeColor = ConsoleColor.DarkRed
                });
                console.AddMapping(
                    new ManagedColoredConsoleAppender.LevelColors {
                    Level = Level.Warn, ForeColor = ConsoleColor.DarkYellow
                });

                layoutConsole.ActivateOptions();
                console.Layout = layoutConsole;
                console.ActivateOptions();
                repository.Root.AddAppender(console);
            }

            //MemoryAppender memory = new MemoryAppender();
            //memory.ActivateOptions();
            //repository.Root.AddAppender(memory);

            //repository.Root.Level = Level.Debug;
            repository.Configured = true;
        }
Пример #11
0
        //IBlazorApplicationBuilder
        //IComponentsApplicationBuilder
        public void Configure(IComponentsApplicationBuilder app)
        {
            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");

            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);
            };
        }
Пример #12
0
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("app");

            builder.Services.AddTransient(sp => new HttpClient
            {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });

            builder.Services.AddFileReaderService(options => options.UseWasmSharedBuffer = true);

            builder.Services.AddStorage();

            builder.Services.AddSpeechSynthesis();

            builder.Services.AddScoped <IIndexedDbFactory, IndexedDbFactory>();

            builder.Services.AddWorkerFactory();

            builder.Services.AddToaster(config =>
            {
                //example customizations
                config.PositionClass     = Defaults.Classes.Position.TopRight;
                config.PreventDuplicates = true;
                config.NewestOnTop       = true;
            });

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



                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 =
                    log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


                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);
                };
            }

            await builder.Build().RunAsync();
        }
Пример #13
0
        /// <summary>
        /// Receives the raw conversion pattern from the Log4Net config file, and generates the necessary <see cref="LogLineField"/> information.
        /// </summary>
        /// <param name="rawConversionPattern">The raw conversion pattern string.</param>
        private static List <LogLineField> GenerateFieldsFromConversionPattern(string rawConversionPattern)
        {
            List <LogLineField> newFields = new List <LogLineField>();

            List <string> fieldPatterns = new List <string>();

            int  startPos = 0;
            bool inField  = false;

            for (int i = 0; i < rawConversionPattern.Length; i++)
            {
                if ((rawConversionPattern[i] == ' ' || i == rawConversionPattern.Length - 1) &&
                    inField)
                {
                    fieldPatterns.Add(rawConversionPattern.Substring(startPos, i - startPos).Trim());
                    inField = false;
                    continue;
                }

                if (rawConversionPattern[i] != '%')
                {
                    continue;
                }

                if (inField)
                {
                    fieldPatterns.Add(rawConversionPattern.Substring(startPos, i - startPos).Trim());
                    inField = false;
                }

                startPos = i;
                inField  = true;
            }

            foreach (string pattern in fieldPatterns)
            {
                string cleanedPattern = PatternLayout.CleanConversionPatternField(pattern);

                bool inPadding  = false;
                bool inTruncate = false;

                string paddingElement  = string.Empty;
                string truncateElement = string.Empty;
                string patternElement  = string.Empty;

                foreach (char c in cleanedPattern)
                {
                    if (c == '.')
                    {
                        inPadding  = false;
                        inTruncate = true;
                        continue;
                    }

                    if (Char.IsDigit(c))
                    {
                        if (!inTruncate)
                        {
                            inPadding = true;
                        }
                        else
                        {
                            truncateElement += c;
                        }

                        if (inPadding)
                        {
                            paddingElement += c;
                        }

                        continue;
                    }

                    inPadding       = inTruncate = false;
                    patternElement += c;
                }

                if (string.IsNullOrEmpty(patternElement))
                {
                    continue;
                }

                LogLineField newField = new LogLineField
                {
                    Name = PatternLayout.RetrieveFieldNameFromConversionPattern(patternElement)
                };

                if (!string.IsNullOrEmpty(truncateElement))
                {
                    newField.Type       = LogLineType.FixedWidth;
                    newField.FixedWidth = int.Parse(truncateElement);
                }
                else
                {
                    newField.Type            = LogLineType.Delimited;
                    newField.EndingCharacter = ' ';

                    if (!string.IsNullOrEmpty(paddingElement))
                    {
                        newField.MinWidth = int.Parse(paddingElement);
                    }
                }

                newFields.Add(newField);
            }

            return(newFields);
        }
Пример #14
0
        // ------------------------------------------------------------------------------------------------------------------------
        //  Initialize and start log4net
        // ------------------------------------------------------------------------------------------------------------------------
        public static void InitializeLog4net(string logFilename = null, Level logLevel = null)
        {
            if (logFilename == null)
            {
                logFilename = @"'logs\WinFCU_'yyyyMMdd'.log'";
            }
            if (logLevel == null)
            {
                logLevel = (cli.IsPresent("Debug") && !cli.IsNegated("Debug")) ? Level.Debug : Level.Info;
            }
            // --------------------------------------------------------------------------------------------------------------------
            //  See whether a 'customer' log4net configuration has been provided. When present use it
            // --------------------------------------------------------------------------------------------------------------------
            ConfigurationSection l4nSection = total.APP.Configuration.GetSection("log4net");

            if (l4nSection != null)
            {
                log4net.Config.XmlConfigurator.Configure();
                Log4netSetRootLevel(logLevel);
                total.Logger.Debug("Using customer specific log4net configuration");
            }
            // --------------------------------------------------------------------------------------------------------------------
            //   Configure the default logger (console and rolling logfile)
            // --------------------------------------------------------------------------------------------------------------------
            else
            {
                // ----------------------------------------------------------------------------------------------------------------
                //   Reset the current log config and start a new one
                // ----------------------------------------------------------------------------------------------------------------
                if (total.Logger != null)
                {
                    total.Logger.Logger.Repository.ResetConfiguration();
                }
                Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
#pragma warning disable IDE0017 // Simplify object initialization
                PatternLayout patternLayout = new PatternLayout();
#pragma warning restore IDE0017 // Simplify object initialization
                patternLayout.ConversionPattern = "%date{yyyy-MM-dd HH:mm:ss} - %-5level - %m%n";
                patternLayout.ActivateOptions();
                // ----------------------------------------------------------------------------------------------------------------
                //   Create a RollingLogfileAppender
                // ----------------------------------------------------------------------------------------------------------------
#pragma warning disable IDE0017 // Simplify object initialization
                RollingFileAppender rlfa = new RollingFileAppender();
#pragma warning restore IDE0017 // Simplify object initialization
                rlfa.Name              = "WinFCU-RollingLogfileAppender";
                rlfa.File              = logFilename;
                rlfa.AppendToFile      = true;
                rlfa.StaticLogFileName = false;
                rlfa.RollingStyle      = RollingFileAppender.RollingMode.Date;
                rlfa.Layout            = patternLayout;
                rlfa.Threshold         = logLevel;
                rlfa.ActivateOptions();
                // ----------------------------------------------------------------------------------------------------------------
                //   Create a ManagedColoredConsoleAppender
                // ----------------------------------------------------------------------------------------------------------------
#pragma warning disable IDE0017 // Simplify object initialization
                ManagedColoredConsoleAppender mcca = new ManagedColoredConsoleAppender();
#pragma warning restore IDE0017 // Simplify object initialization
                mcca.Name = "WinFCU-ManagedColoredConsoleAppender";
                mcca.AddMapping(new ManagedColoredConsoleAppender.LevelColors {
                    Level = Level.Fatal, ForeColor = ConsoleColor.Magenta, BackColor = ConsoleColor.Black
                });
                mcca.AddMapping(new ManagedColoredConsoleAppender.LevelColors {
                    Level = Level.Error, ForeColor = ConsoleColor.Red, BackColor = ConsoleColor.Black
                });
                mcca.AddMapping(new ManagedColoredConsoleAppender.LevelColors {
                    Level = Level.Warn, ForeColor = ConsoleColor.Yellow, BackColor = ConsoleColor.Black
                });
                mcca.AddMapping(new ManagedColoredConsoleAppender.LevelColors {
                    Level = Level.Info, ForeColor = ConsoleColor.Gray
                });
                mcca.AddMapping(new ManagedColoredConsoleAppender.LevelColors {
                    Level = Level.Debug, ForeColor = ConsoleColor.Green, BackColor = ConsoleColor.Gray
                });
                mcca.Layout    = patternLayout;
                mcca.Threshold = logLevel;
                mcca.ActivateOptions();
                // ----------------------------------------------------------------------------------------------------------------
                //   Build the hierarchy and start it
                // ----------------------------------------------------------------------------------------------------------------
                hierarchy.Root.AddAppender(rlfa);
                hierarchy.Root.AddAppender(mcca);
                hierarchy.Configured = true;
                // ----------------------------------------------------------------------------------------------------------------
                //   Finaly inform the audience we are working with an embedded log4net configuration
                // ----------------------------------------------------------------------------------------------------------------
                total.Logger.Warn(" >>>> WinFCU - No customer log4net configuration found! Using embedded configuration settings");
            }
        }
Пример #15
0
        public VisualStudioOutputWindowAppender(IVisualStudioWriter outputWindow)
        {
            OutputWindow = outputWindow;

            Layout = new PatternLayout("%-5level %logger - %message%newline");
        }
Пример #16
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.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
    }
Пример #17
0
    protected override void OnStart(string[] args)
    {
        #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 busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.FirstEndpoint");

        #endregion

        #region container

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

        #endregion

        #region serialization

        busConfiguration.UseSerialization <XmlSerializer>();

        #endregion

        #region transport

        busConfiguration.UseTransport <MsmqTransport>();

        #endregion

        #region persistence

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

        #endregion

        #region critical-errors

        busConfiguration.DefineCriticalErrorAction(
            onCriticalError: (errorMessage, exception) =>
        {
            // Log the critical error
            log.Fatal($"CRITICAL: {errorMessage}", exception);

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

        #endregion

        #region start-bus

        busConfiguration.EnableInstallers();
        bus = Bus.Create(busConfiguration).Start();

        #endregion


        var myMessage = new MyMessage();
        bus.SendLocal(myMessage);
    }
Пример #18
0
    static void Main()
    {
        #region ConfigureLog4Net

        PatternLayout layout = new PatternLayout
        {
            ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"
        };
        layout.ActivateOptions();
        ColoredConsoleAppender consoleAppender = new ColoredConsoleAppender
        {
            Threshold = Level.Info,
            Layout    = layout
        };
        // Note that no consoleAppender.ActivateOptions(); is required since NSB 4 does this internally

        RollingFileAppender fileAppender = new RollingFileAppender
        {
            DatePattern        = "yyyy-MM-dd'.txt'",
            RollingStyle       = RollingFileAppender.RollingMode.Composite,
            MaxFileSize        = 10 * 1024 * 1024,
            MaxSizeRollBackups = 10,
            LockingModel       = new FileAppender.MinimalLock(),
            StaticLogFileName  = false,
            File         = @"nsblog2",
            Layout       = layout,
            AppendToFile = true,
            Threshold    = Level.Info,
        };
        // Note that no fileAppender.ActivateOptions(); is required since NSB 4 does this internally
        BasicConfigurator.Configure(fileAppender, consoleAppender);

        #endregion

        Configure.Serialization.Json();

        #region UseConfig

        Configure configure = Configure.With();
        configure.DefineEndpointName("Samples.Logging.Log4NetCustom");

        //Pass the appenders to NServiceBus
        configure.Log4Net(consoleAppender);
        configure.Log4Net(fileAppender);

        #endregion

        configure.DefaultBuilder();
        configure.InMemorySagaPersister();
        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();
        configure.UseTransport <Msmq>();
        using (IStartableBus startableBus = configure.UnicastBus().CreateBus())
        {
            IBus bus = startableBus.Start(() => configure.ForInstallationOn <Windows>().Install());
            bus.SendLocal(new MyMessage());

            Console.WriteLine("\r\nPress any key to stop program\r\n");
            Console.ReadKey();
        }
    }
Пример #19
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("Samples.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
            string output = string.Format("The following critical error was encountered by NServiceBus:\n{0}\nNServiceBus is shutting down.", errorMessage);
            Environment.FailFast(output, exception);
        });
        #endregion

        #region start-bus
        busConfiguration.EnableInstallers();
        bus = Bus.Create(busConfiguration).Start();
        #endregion
    }
Пример #20
0
        /// <summary>
        ///     Warning: this is not tread-safe, so only call this at startup or at a time that you are sure your
        ///     process is not performing any logging!
        /// </summary>
        /// <param name="filePath">The path to the log file.</param>
        /// <param name="sourceLevels">The lowest log level to log.</param>
        public static void SetLogFilePath(string filePath, SourceLevels sourceLevels)
        {
            if (!System.IO.Path.IsPathRooted(filePath))
            {
                filePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                                                  System.IO.Path.Combine(@"SatIp RtspSample\Logs", filePath));
            }

            Level level = Level.Debug;

            if (_sourceLevels == SourceLevels.Information)
            {
                level = Level.Info;
            }
            else if (_sourceLevels == SourceLevels.Warning)
            {
                level = Level.Warn;
            }
            else if (_sourceLevels == SourceLevels.Error)
            {
                level = Level.Error;
            }
            else if (_sourceLevels == SourceLevels.Critical)
            {
                level = Level.Fatal;
            }
            _sourceLevels = sourceLevels;

            var hierarchy =
                (log4Hierarchy.Hierarchy)LogManager.GetAllRepositories().FirstOrDefault(r => r.Name == Path) ??
                (log4Hierarchy.Hierarchy)LogManager.CreateRepository(Path);

            hierarchy.Root.RemoveAllAppenders();

            var roller        = new RollingFileAppender();
            var patternLayout = new PatternLayout {
                ConversionPattern = "%date [%-5level][%thread]: %message%newline"
            };

            patternLayout.ActivateOptions();
            roller.Layout             = patternLayout;
            roller.AppendToFile       = true;
            roller.RollingStyle       = RollingFileAppender.RollingMode.Size;
            roller.MaxSizeRollBackups = 4;
            roller.MaximumFileSize    = "1000KB";
            roller.StaticLogFileName  = true;
            roller.File = filePath;
            roller.ActivateOptions();
            roller.AddFilter(new LevelRangeFilter
            {
                LevelMin = level,
                LevelMax = Level.Fatal
            });
            BasicConfigurator.Configure(hierarchy, roller);

            var coreLogger = hierarchy.GetLogger(Path) as log4Hierarchy.Logger;

            if (coreLogger != null)
            {
                coreLogger.Level = level;
            }

            _log = LogManager.GetLogger(hierarchy.Name, Path);
        }
Пример #21
0
        public AppenderBuilder SetLayout(string layoutString)
        {
            PatternLayout layout = new PatternLayout(layoutString);

            return(this.SetLayout(layout));
        }
Пример #22
0
 public CustomLabelPattern(string key, PatternLayout layout)
 {
     Key    = key;
     Layout = layout;
 }
Пример #23
0
        /// <summary>
        /// mail#info
        /// </summary>
        /// <param name="repositoryName"></param>
        /// <returns></returns>
        private ILog GetLogger(string repositoryName, Level level)
        {
            if (string.IsNullOrEmpty(repositoryName))
            {
                return(LogManager.GetLogger("Defalut"));
            }

            string            getkey     = repositoryName + level.ToString();
            ILoggerRepository repository = null;

            try
            {
                repository = LogManager.GetRepository(getkey);
            }
            catch (Exception) { }

            //找到直接返回ilog
            if (repository != null)
            {
                return(LogManager.GetLogger(getkey, "Defalut"));
            }

            //未找到则创建,多线程下很有可能创建时,就存在了
            try
            {
                repository = LogManager.CreateRepository(getkey);
            }
            catch (Exception)
            {
                repository = LogManager.GetRepository(getkey);
            }


            #region create fileappender
            if (this.IncludeFile)
            {
                //查找输出Appender
                RollingFileAppender fileAppender = new RollingFileAppender();
                fileAppender.Name              = "RollingFileAppender_" + getkey;
                fileAppender.RollingStyle      = RollingFileAppender.RollingMode.Date;
                fileAppender.AppendToFile      = true;
                fileAppender.DatePattern       = "yyyyMMdd'.txt'";
                fileAppender.StaticLogFileName = false;
                //\\mail\info\ \mail\error

                if (repositoryName.ToLower().EndsWith("info"))
                {
                    repository.Threshold = Level.Info;
                }
                if (repositoryName.ToLower().EndsWith("error"))
                {
                    repository.Threshold = Level.Error;
                }
                else
                {
                    repository.Threshold = Level.All;
                }

                PatternLayout patternLayout = new PatternLayout();

                patternLayout.Header = "";
                //patternLayout.ConversionPattern = "记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline";
                patternLayout.ConversionPattern = "%date [msg: %message] %newline";
                patternLayout.ActivateOptions();
                fileAppender.Layout = patternLayout;

                string file = AppDomain.CurrentDomain.BaseDirectory + "_logs\\" + repositoryName + "\\";
                if (!string.IsNullOrEmpty(AppID) && !string.IsNullOrEmpty(AppID))
                {
                    file = AppDomain.CurrentDomain.BaseDirectory + "\\_logs\\" + AppID + "\\" + repositoryName + "\\";
                }

                LevelRangeFilter lrf = new LevelRangeFilter();
                if (level == Level.Info)
                {
                    lrf.LevelMin = Level.All;
                    lrf.LevelMax = Level.Info;
                    file        += "info\\";
                }
                else if (level == Level.Error)
                {
                    lrf.LevelMin = Level.Error;
                    lrf.LevelMax = Level.Fatal;
                    file        += "error\\";
                }
                else if (level == Level.Debug)
                {
                    lrf.LevelMin = Level.Debug;
                    lrf.LevelMax = Level.Debug;
                    file        += "debug\\";
                }
                else
                {
                    lrf.LevelMin = Level.All;
                    lrf.LevelMax = Level.Fatal;
                    file        += "other\\";
                }

                fileAppender.AddFilter(lrf);
                fileAppender.File = file;

                //LevelMatchFilter lmf = new LevelMatchFilter();

                //if (repositoryName.ToLower().EndsWith("info"))
                //    lmf.LevelToMatch = Level.Info;
                //if (repositoryName.ToLower().EndsWith("error"))
                //    lmf.LevelToMatch = Level.Error;
                //else
                //    lmf.LevelToMatch = Level.All;

                //选择UTF8编码,确保中文不乱码。
                fileAppender.Encoding = System.Text.Encoding.UTF8;
                fileAppender.ActivateOptions();

                BasicConfigurator.Configure(repository, fileAppender);
            }
            #endregion

            if (this.IncludeDB)
            {
                IAppender adoAppender = GetAdoLogger(repository);
                if (adoAppender != null)
                {
                    BasicConfigurator.Configure(repository, adoAppender);
                }
            }


            //  return LogManager.GetLogger(getkey, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            return(LogManager.GetLogger(getkey, getkey));
        }
Пример #24
0
        static void Main(string[] args)
        {
            var            files   = new List <string>();
            int            monitor = 0;
            int?           lines   = null;
            var            watch   = false;
            LayoutSkeleton layout  = null;
            var            help    = false;
            var            p       = new OptionSet()
            {
                { "i|file=", v => { files.Add(v); } },
                { "m|monitor=", v => { monitor = ParseInterval(v); } },
                { "w|watch", v => { watch = true; } },
                { "l|lines=", v => { lines = Int32.Parse(v); } },
                { "h|?|help", v => { help = true; } },
                { "y|layout=", v => { layout = new PatternLayout(v); } },
                { "f|format=", v => { layout = GetFormatLayout(v); } }
            };
            var detectedFiles = args
                                .Where(a => !(a.StartsWith("-") || a.StartsWith("/")))
                                .Where(a => File.Exists(a));

            files.AddRange(detectedFiles);

            p.Parse(args);
            if (layout == null)
            {
                layout = new SimpleLayout();
            }
            Action <TextWriter, LogEntry> showentry = (writer, l) => layout.Format(writer, new LoggingEvent(l.Data));

            if (help)
            {
                Console.WriteLine(@"Usage:
-i|file={a filename}
    The (input) file to watch, monitor or 

-l|lines={tail x lines}	
    Display the last x lines. Defaults to 10 lines. 

-y|layout={pattern layout syntax as defined in log4net.Layout.PatternLayout}

-f|format={a named layout format}
    The available formats are:
        -f=minusminus Information delimited by newline and ----------------------

-h|?|help
    Display help

-w|watch
    Use file system watcher to watch file

-m|monitor=seconds
    Use polling to check for changes of the file.

For instance to :
LogTail.exe -f=logfile.xml
LogTail.exe -file=logfile.xml

If you are in powershell (or cygwin) you can do the following:
cat yourlogfile.xml | LogTail.exe
");
                return;
            }

            if (watch)
            {
                var w = new Watcher <LogEntry>(new FileWithPosition(files.Single()), new LogEntryParser());
                w.LogEntry += (entry) => showentry(Console.Out, entry);

                Do(w);
                return;
            }
            if (monitor > 0)
            {
                var w = new Poller <LogEntry>(new FileWithPosition(files.Single()), monitor, new LogEntryParser());
                w.LogEntry += (entry) => showentry(Console.Out, entry);
                Do(w);
                return;
            }

            if (files.Any())
            {
                TailFiles(lines ?? 10, files, (entry) => showentry(Console.Out, entry));
                return;
            }
            else
            {
                Console.WriteLine("No files, listening to standard input.");
                using (Stream stdin = Console.OpenStandardInput())
                    using (Stream stdout = Console.OpenStandardOutput())
                        using (StreamWriter writer = new StreamWriter(stdout))
                        {
                            var items = new LogEntryParser().Parse(stdin).ToArray();
                            foreach (var logEntry in items.Skip(items.Count() - (lines ?? 10)))
                            {
                                showentry(writer, logEntry);
                            }
                        }
                return;
            }
        }
Пример #25
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 arguments = "/elevated " +
#if VNEXT
                                   " " + (stdinName ?? NoPipe) +
                                   " " + (stdoutName ?? NoPipe) +
                                   " " + (stderrName ?? NoPipe) +
#endif
#if NET
                                   string.Join(' ', args);
#elif !NET20
                                   string.Join(" ", args);
#else
                                   string.Join(" ", args.ToArray());
#endif

                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()
Пример #26
0
        protected void ConfigureAppenders(string fileName)
        {
            //Get the logger repository hierarchy.
            if (!(LogManager.GetRepository(Assembly.GetCallingAssembly()) is Hierarchy repository))
            {
                throw new Exception("log4net repository was not configured");
            }

            if (!(repository.GetLogger(_loggerName) is Logger logger))
            {
                throw new Exception($"Logger '{_loggerName}' not found");
            }

            #region Configure signalRAppender

            if (logger.Appenders.OfType <SignalrAppender>().All(a => a.GroupName != _logGroupName))
            {
                //var hub = GlobalHost.ConnectionManager.GetHubContext<SignalrAppenderHub>();
                var hubContext      = _iocResolver.Resolve <IHubContext <SignalrAppenderHub> >();
                var signalrAppender = new SignalrAppender(hubContext, _logGroupName)
                {
                    Name      = _loggerName + "SignalrAppenderAuto",
                    Threshold = Level.All,
                };

                var signalrLayout = new PatternLayout()
                {
                    ConversionPattern = "%d - %m%n%n"
                };

                signalrLayout.ActivateOptions();
                signalrAppender.Layout = signalrLayout;
                signalrAppender.ActivateOptions();

                logger.AddAppender(signalrAppender);
            }

            #endregion

            #region Configure file appender

            if (!string.IsNullOrWhiteSpace(fileName))
            {
                var fileAppender = new FileAppender
                {
                    Name         = _loggerName + "FileAppenderAuto",
                    File         = fileName,
                    AppendToFile = false,
                    Threshold    = Level.All,
                    LockingModel = new FileAppender.MinimalLock()
                };
                //new log4net.Util.PatternString("D:\Temp\Logs\%property{LogName}.log")

                var fileLayout = new PatternLayout()
                {
                    ConversionPattern = "%d - %m%n%n"
                };

                fileLayout.ActivateOptions();
                fileAppender.Layout = fileLayout;
                fileAppender.ActivateOptions();

                logger.AddAppender(fileAppender);
            }

            #endregion

            // Mark repository as configured and notify that is has changed.
            repository.Configured = true;
            repository.RaiseConfigurationChanged(EventArgs.Empty);

            _logger = LogManager.GetLogger(Assembly.GetCallingAssembly(), _loggerName);
        }
Пример #27
0
        public static void Setup(Level level, string logPath, string id)
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetEntryAssembly());

            hierarchy.Root.RemoveAllAppenders();

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date{HH:mm:ss,fff},%level,%message%newline";
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();

            roller.AppendToFile       = false;
            roller.File               = Path.Combine(logPath, $"extractlog_{id}.csv");
            roller.Layout             = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize    = "1MB";
            roller.RollingStyle       = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName  = true;
            roller.ActivateOptions();

            PatternLayout patternLayout2 = new PatternLayout();

            patternLayout2.ConversionPattern = "%level,%message%newline";
            patternLayout2.ActivateOptions();

            ManagedColoredConsoleAppender console = new ManagedColoredConsoleAppender();
            var l1 = new LevelColors
            {
                ForeColor = ConsoleColor.Green,
                Level     = Level.Fatal
            };
            var l2 = new LevelColors
            {
                ForeColor = ConsoleColor.Red,
                Level     = Level.Error
            };
            var l3 = new LevelColors
            {
                ForeColor = ConsoleColor.Yellow,
                Level     = Level.Warn
            };
            var l4 = new LevelColors
            {
                ForeColor = ConsoleColor.White,
                Level     = Level.Info
            };
            var l5 = new LevelColors
            {
                ForeColor = ConsoleColor.White,
                Level     = Level.Debug
            };

            console.AddMapping(l1);
            console.AddMapping(l2);
            console.AddMapping(l3);
            console.AddMapping(l4);
            console.AddMapping(l5);
            console.Layout = patternLayout2;
            console.ActivateOptions();
            hierarchy.Root.Level = level;
            BasicConfigurator.Configure(hierarchy, roller, console);
        }
		/// <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;
		}
Пример #29
0
    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>(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()
            .ConfigureAwait(false);

            // 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();
        endpointInstance = await Endpoint.Start(endpointConfiguration)
                           .ConfigureAwait(false);

        #endregion

        var myMessage = new MyMessage();
        await endpointInstance.SendLocal(myMessage)
        .ConfigureAwait(false);
    }