public void EntLib5UseCase()
        {
            // construct the Configuration Source to use
            var builder = new ConfigurationSourceBuilder();

            // fluent API configuration
            builder.ConfigureLogging()
            .WithOptions
            .DoNotRevertImpersonation()
            .LogToCategoryNamed("Simple")
            .SendTo.FlatFile("Simple Log File")
            .FormatWith(new FormatterBuilder()
                        .TextFormatterNamed("simpleFormat")
                        .UsingTemplate("{timestamp} : {message}{newline}"))
            .ToFile("simple.log");

            var configSource = new DictionaryConfigurationSource();

            builder.UpdateConfigurationWithReplace(configSource);
            EnterpriseLibraryContainer.Current
                = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

            ILog log = LogManager.GetLogger(GetType());

            log.Debug("Debug Event Log Entry.");
            log.Warn("Warning Event Log Entry.");
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            // 構成情報を組み立てる
            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
            .SpecialSources
            .AllEventsCategory
            .SendTo
            .FlatFile("FlatFileListener")
            .FormatWith(
                new FormatterBuilder()
                .TextFormatterNamed("TextFormatter")
                .UsingTemplate("{timestamp(local:yyyy/MM/dd HH:mm:ss.fff)}: {message}"))
            .ToFile("output.txt");

            // 組み立てた構成情報からIServiceLocatorを作成
            EnterpriseLibraryContainer.Current = builder.CreateContainer();

            // EnterpriseLibraryのコンテナからLogging Application BlockのLog書き込み部品を取得
            var logger = EnterpriseLibraryContainer.Current.GetInstance <LogWriter>();

            // ログに出力する
            logger.Write("Hello world");

            // ログを表示
            Process.Start("output.txt");
        }
Beispiel #3
0
        protected override void Arrange()
        {
            base.Arrange();

            ConfigurationSourceBuilder sourceBuilder = new ConfigurationSourceBuilder();

            sourceBuilder
            .ConfigureLogging()
            .WithOptions
            .FilterCustom <MockLogFilter>("filter")
            .LogToCategoryNamed("General")
            .SendTo
            .SystemDiagnosticsListener("listener")
            .SendTo
            .Msmq("msmqlistener")
            .LogToCategoryNamed("Other")
            .SendTo
            .EventLog("eventlog");;

            DesignDictionaryConfigurationSource source = new DesignDictionaryConfigurationSource();

            sourceBuilder.UpdateConfigurationWithReplace(source);

            var sourceModel = Container.Resolve <ConfigurationSourceModel>();

            sourceModel.Load(source);

            LoggingSectionViewModel = sourceModel.Sections.Where(x => x.SectionName == LoggingSettings.SectionName).First();
        }
        protected override void Arrange()
        {
            base.Arrange();

            IConfigurationSource source = new DictionaryConfigurationSource();
            ConfigurationSourceBuilder sourceBuiler = new ConfigurationSourceBuilder();

            sourceBuiler.ConfigureLogging()
                .WithOptions.DisableTracing()
                .DoNotRevertImpersonation()
                .FilterOnPriority("prio filter").StartingWithPriority(10)
                .FilterOnCategory("categoryFiler").AllowAllCategoriesExcept("cat1")
                .LogToCategoryNamed("General")
                .SendTo.EventLog("Event Log Listener")
                .FormatWith(new FormatterBuilder().TextFormatterNamed("Default"))
                .LogToCategoryNamed("Critical")
                .SendTo.SharedListenerNamed("Event Log Listener")
                .SendTo.Custom<MyCustomListener>("Custom Listener")
                .SendTo.Email("Email Listener")
                .SendTo.SystemDiagnosticsListener("system diagnostics")
                .LogToCategoryNamed("msmq")
                .SendTo.Msmq("msmq");

            sourceBuiler.UpdateConfigurationWithReplace(source);
            LoggingSection = (LoggingSettings)source.GetSection(LoggingSettings.SectionName);
        }
        public void EntLib5FactoryTestWithFluentConfig()
        {
            // construct the Configuration Source to use
            var builder = new ConfigurationSourceBuilder();

            // fluent API configuration
            builder.ConfigureLogging()
                .WithOptions
                    .DoNotRevertImpersonation()
                .LogToCategoryNamed("Simple")
                    .SendTo.FlatFile("Simple Log File")
                     .FormatWith(new FormatterBuilder()
                        .TextFormatterNamed("simpleFormat")
                            .UsingTemplate("{timestamp} : {message}{newline}"))
                     .ToFile("simple.log");

            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);
            EnterpriseLibraryContainer.Current
                = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

            // initialize the EntLib5 Logger factory with configuration file
            EntLib5Factory factory = new EntLib5Factory();

            ILog log = factory.GetLogger(GetType());
            Assert.IsNotNull(log);
            Assert.IsNotNull(log as EntLib5Logger);
        }
Beispiel #6
0
        public void EntLib5FactoryTestWithFluentConfig()
        {
            // construct the Configuration Source to use
            var builder = new ConfigurationSourceBuilder();

            // fluent API configuration
            builder.ConfigureLogging()
            .WithOptions
            .DoNotRevertImpersonation()
            .LogToCategoryNamed("Simple")
            .SendTo.FlatFile("Simple Log File")
            .FormatWith(new FormatterBuilder()
                        .TextFormatterNamed("simpleFormat")
                        .UsingTemplate("{timestamp} : {message}{newline}"))
            .ToFile("simple.log");

            var configSource = new DictionaryConfigurationSource();

            builder.UpdateConfigurationWithReplace(configSource);
            EnterpriseLibraryContainer.Current
                = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

            // initialize the EntLib5 Logger factory with configuration file
            EntLib5Factory factory = new EntLib5Factory();

            ILog log = factory.GetLogger(GetType());

            Assert.IsNotNull(log);
            Assert.IsNotNull(log as EntLib5Logger);
        }
Beispiel #7
0
        protected override void Arrange()
        {
            base.Arrange();

            IConfigurationSource       source       = new DictionaryConfigurationSource();
            ConfigurationSourceBuilder sourceBuiler = new ConfigurationSourceBuilder();

            sourceBuiler.ConfigureLogging()
            .WithOptions.DisableTracing()
            .DoNotRevertImpersonation()
            .FilterOnPriority("prio filter").StartingWithPriority(10)
            .FilterOnCategory("categoryFiler").AllowAllCategoriesExcept("cat1")
            .LogToCategoryNamed("General")
            .SendTo.EventLog("Event Log Listener")
            .FormatWith(new FormatterBuilder().TextFormatterNamed("Default"))
            .LogToCategoryNamed("Critical")
            .SendTo.SharedListenerNamed("Event Log Listener")
            .SendTo.Custom <MyCustomListener>("Custom Listener")
            .SendTo.Email("Email Listener")
            .SendTo.SystemDiagnosticsListener("system diagnostics")
            .LogToCategoryNamed("msmq")
            .SendTo.Msmq("msmq");

            sourceBuiler.UpdateConfigurationWithReplace(source);
            LoggingSection = (LoggingSettings)source.GetSection(LoggingSettings.SectionName);
        }
        private void ConfigureLogging()
        {
            var configurationSource = new DictionaryConfigurationSource();
            var builder = new ConfigurationSourceBuilder();
            const string DefaultListenerName = "Default";

            builder.ConfigureLogging()
                .WithOptions
                    .DoNotRevertImpersonation()
                .SpecialSources
                    .LoggingErrorsAndWarningsCategory
                        .SendTo.SharedListenerNamed(DefaultListenerName)
                .SpecialSources
                    .UnprocessedCategory
                        .SendTo.SharedListenerNamed(DefaultListenerName)
                .SpecialSources
                    .AllEventsCategory
                        .SendTo.SharedListenerNamed(DefaultListenerName)
                .LogToCategoryNamed("General")
                    .WithOptions.SetAsDefaultCategory()
                    .SendTo.SharedListenerNamed(DefaultListenerName);
            builder.UpdateConfigurationWithReplace(configurationSource);

            var configurator = new UnityContainerConfigurator(this.Container);
            EnterpriseLibraryContainer.ConfigureContainer(configurator, configurationSource);

            this.Container.RegisterType<TraceListener, CommonLoggingEntlibTraceListener>(
                DefaultListenerName,
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(this.CreateListener));
        }
        protected override void Arrange()
        {
            base.Arrange();

            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
            .LogToCategoryNamed("category")
            .SendTo
            .EventLog("listener")
            .SpecialSources
            .AllEventsCategory
            .SendTo
            .EventLog("listener")
            .SpecialSources
            .LoggingErrorsAndWarningsCategory
            .SendTo
            .EventLog("listener")
            .SpecialSources
            .UnprocessedCategory
            .SendTo
            .EventLog("listener");


            var source = new DictionaryConfigurationSource();

            builder.UpdateConfigurationWithReplace(source);

            ElementLookup  = Container.Resolve <ElementLookup>();
            LoggingSection = (LoggingSettings)source.GetSection(LoggingSettings.SectionName);
        }
        protected override void Arrange()
        {
            base.Arrange();

            ConfigurationSourceBuilder sourceBuilder = new ConfigurationSourceBuilder();

            sourceBuilder
                .ConfigureLogging()
                .WithOptions
                .FilterCustom<MockLogFilter>("filter")
                .LogToCategoryNamed("General")
                .SendTo
                .SystemDiagnosticsListener("listener")
                .SendTo
                .Msmq("msmqlistener")
                .LogToCategoryNamed("Other")
                .SendTo
                .EventLog("eventlog"); ;

            DesignDictionaryConfigurationSource source = new DesignDictionaryConfigurationSource();
            sourceBuilder.UpdateConfigurationWithReplace(source);

            var sourceModel = Container.Resolve<ConfigurationSourceModel>();
            sourceModel.Load(source);

            LoggingSectionViewModel = sourceModel.Sections.Where(x => x.SectionName == LoggingSettings.SectionName).First();
        }
        protected override void Arrange()
        {
            base.Arrange();

            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
                .LogToCategoryNamed("General")
                    .SendTo.EventLog("Event Log Listener")
                    .FormatWith(new FormatterBuilder().TextFormatterNamed("Text Formatter"))
                    .ToLog("Application");

            builder.ConfigureExceptionHandling()
                    .GivenPolicyWithName("AllExceptions")
                        .ForExceptionType<Exception>()
                            .LogToCategory("General")
                            .ThenDoNothing()
                    .GivenPolicyWithName("OtherExceptions")
                        .ForExceptionType<ArgumentNullException>()
                            .LogToCategory("InvalidCategoryName")
                            .ThenDoNothing();


            var configuration = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configuration);

            LoggingSection = GetSection(LoggingSettings.SectionName, configuration);
            ExceptionHandlingSection = GetSection(ExceptionHandlingSettings.SectionName, configuration);
        }
        public void EntLib5UseCase()
        {
            // construct the Configuration Source to use
            var builder = new ConfigurationSourceBuilder();

            // fluent API configuration
            builder.ConfigureLogging()
                .WithOptions
                    .DoNotRevertImpersonation()
                .LogToCategoryNamed("Simple")
                    .SendTo.FlatFile("Simple Log File")
                     .FormatWith(new FormatterBuilder()
                        .TextFormatterNamed("simpleFormat")
                            .UsingTemplate("{timestamp} : {message}{newline}"))
                     .ToFile("simple.log");

            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);
            EnterpriseLibraryContainer.Current
                = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

            ILog log = LogManager.GetLogger(GetType());

            log.Debug("Debug Event Log Entry.");
            log.Warn("Warning Event Log Entry.");

        }
        protected override void Arrange()
        {
            base.Arrange();

            ConfigurationSourceBuilder sourceBuilder = new ConfigurationSourceBuilder();

            sourceBuilder.ConfigureLogging().LogToCategoryNamed("General").SendTo.EventLog("Listener").SendTo.Msmq("msmqListener");

            DesignDictionaryConfigurationSource source = new DesignDictionaryConfigurationSource();

            sourceBuilder.UpdateConfigurationWithReplace(source);

            var applicationModel = Container.Resolve <ApplicationViewModel>();
            var sourceModel      = applicationModel.CurrentConfigurationSource;

            sourceModel.Load(source);
            foreach (var element in sourceModel.Sections.SelectMany(x => x.DescendentElements()))
            {
                element.InheritedFromParentConfiguration = false;
            }

            applicationModel.NewEnvironment();
            Environment = applicationModel.Environments.First();

            LoggingSectionViewModel = sourceModel.Sections.Where(x => x.SectionName == LoggingSettings.SectionName).First();
        }
Beispiel #14
0
        private void ConfigureLogging()
        {
            var          configurationSource = new DictionaryConfigurationSource();
            var          builder             = new ConfigurationSourceBuilder();
            const string DefaultListenerName = "Default";

            builder.ConfigureLogging()
            .WithOptions
            .DoNotRevertImpersonation()
            .SpecialSources
            .LoggingErrorsAndWarningsCategory
            .SendTo.SharedListenerNamed(DefaultListenerName)
            .SpecialSources
            .UnprocessedCategory
            .SendTo.SharedListenerNamed(DefaultListenerName)
            .SpecialSources
            .AllEventsCategory
            .SendTo.SharedListenerNamed(DefaultListenerName)
            .LogToCategoryNamed("General")
            .WithOptions.SetAsDefaultCategory()
            .SendTo.SharedListenerNamed(DefaultListenerName);
            builder.UpdateConfigurationWithReplace(configurationSource);

            var configurator = new UnityContainerConfigurator(this.Container);

            EnterpriseLibraryContainer.ConfigureContainer(configurator, configurationSource);

            this.Container.RegisterType <TraceListener, CommonLoggingEntlibTraceListener>(
                DefaultListenerName,
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(this.CreateListener));
        }
        protected override void Arrange()
        {
            base.Arrange();

            var builder = new ConfigurationSourceBuilder();
            builder.ConfigureLogging()
                        .LogToCategoryNamed("category")
                            .SendTo
                                .EventLog("listener")
                        .SpecialSources
                            .AllEventsCategory
                                .SendTo
                                    .EventLog("listener")
                        .SpecialSources
                            .LoggingErrorsAndWarningsCategory
                                .SendTo
                                    .EventLog("listener")
                        .SpecialSources
                            .UnprocessedCategory
                                .SendTo
                                    .EventLog("listener");


            var source = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(source);

            ElementLookup = Container.Resolve<ElementLookup>();
            LoggingSection = (LoggingSettings)source.GetSection(LoggingSettings.SectionName);
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            // 構成情報を組み立てる
            var builder = new ConfigurationSourceBuilder();
            builder.ConfigureLogging()
                .SpecialSources
                .AllEventsCategory
                    .SendTo
                    .FlatFile("FlatFileListener")
                    .FormatWith(
                        new FormatterBuilder()
                            .TextFormatterNamed("TextFormatter")
                            .UsingTemplate("{timestamp(local:yyyy/MM/dd HH:mm:ss.fff)}: {message}"))
                    .ToFile("output.txt");

            // 組み立てた構成情報からConfigurationSourceを作成
            var config = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(config);

            // 構成情報を元にEnterpriseLibraryのコンテナの初期化
            EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(config);

            // EnterpriseLibraryのコンテナからLogging Application BlockのLog書き込み部品を取得
            var logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
            // ログに出力する
            logger.Write("Hello world");

            // ログを表示
            Process.Start("output.txt");
        }
    /// <summary>
    /// Define the logging parameters
    /// </summary>
    public static void DefineLogger()
    {
        var    builder    = new ConfigurationSourceBuilder();
        string loggerPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

        builder.ConfigureLogging()
        .WithOptions
        .DoNotRevertImpersonation()
        .LogToCategoryNamed("LogWriter")
        .WithOptions.SetAsDefaultCategory()
        .SendTo.RollingFile("Rolling Flat File Trace Listener")
        .RollAfterSize(1000)
        .FormatWith(new FormatterBuilder()
                    .TextFormatterNamed("Text Formatter")
                    .UsingTemplate(@"Timestamp: {timestamp}{newline}Message: {message},{newline}Category: {category},{newline}Severity: {severity},{newline}Title:{title},{newline}ProcessId: {localProcessId},{newline}Process Name: {localProcessName},{newline}Thread Name: {threadName}"))
        .ToFile(loggerPath + Properties.Settings.Default.LogFileFolder);
        // Reference app.config
        using (DictionaryConfigurationSource configSource = new DictionaryConfigurationSource())
        {
            builder.UpdateConfigurationWithReplace(configSource);
            LogWriterFactory logWriterFactory = new LogWriterFactory(configSource);
            LogWriter        logWriter        = logWriterFactory.Create();
            Logger.SetLogWriter(new LogWriterFactory(configSource).Create());
        }
    }
        private void configureEntLib()
        {
            var formatterStandard = new FormatterBuilder().TextFormatterNamed("Text Formatter").UsingTemplate(
                "Timestamp: {timestamp}{newline}Message: {message}{newline}Severity: {severity}{newline}Machine: {machine}{newline}Process Name: {processName}{newline}Extended Properties: {dictionary({key} - {value}{newline})}");
            var conf      = new ConfigurationSourceBuilder();
            var logConfig = conf.ConfigureLogging();

            logConfig.WithOptions.LogToCategoryNamed("Exception").SendTo.RollingFile(
                "ExceptionFileListener").WithHeader("----------------------------------------").WithFooter("----------------------------------------").ToFile(UserContext.Settings.ExceptionsLogFile);
            logConfig.WithOptions.LogToCategoryNamed("General").SendTo.RollingFile(
                "FlatFile TraceListener").WithHeader("----------------------------------------").WithFooter("----------------------------------------").FormatWith(formatterStandard).ToFile(UserContext.Settings.StandardLogFile);
            logConfig.WithOptions.LogToCategoryNamed("email").SendTo.Email("email").FormatWith(formatterStandard).UsingSmtpServer(
                ApplicationSettings.MailSmtp).WithUserNameAndPassword(ApplicationSettings.MailUserName,
                                                                      ApplicationSettings.MailPassword).To(
                ApplicationSettings.MailAccount).From(
                ApplicationSettings.MailAccount).UseSSL(true);

            //configure cache
            var cacheCfg = conf.ConfigureCaching();

            cacheCfg.ForCacheManagerNamed(PicturesCache.PicturesCacheName).StoreInIsolatedStorage(
                "Isolated Storage Cache Store").UsePartition("PicturesCache1");

            cacheCfg.ForCacheManagerNamed("ErrorCache").StoreInMemory();

            var configSource = new DictionaryConfigurationSource();

            conf.UpdateConfigurationWithReplace(configSource);

            EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

            BodyArchitect.Logger.Log.EnableExceptionLog = Settings1.Default.LogErrorEnabled;
            BodyArchitect.Logger.Log.EnableStandardLog  = Settings1.Default.LogStandardEnabled;
        }
Beispiel #19
0
        protected override void Arrange()
        {
            base.Arrange();

            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
            .LogToCategoryNamed("General")
            .SendTo.EventLog("Event Log Listener")
            .FormatWith(new FormatterBuilder().TextFormatterNamed("Text Formatter"))
            .ToLog("Application");

            builder.ConfigureExceptionHandling()
            .GivenPolicyWithName("AllExceptions")
            .ForExceptionType <Exception>()
            .LogToCategory("General")
            .ThenDoNothing()
            .GivenPolicyWithName("OtherExceptions")
            .ForExceptionType <ArgumentNullException>()
            .LogToCategory("InvalidCategoryName")
            .ThenDoNothing();


            var configuration = new DictionaryConfigurationSource();

            builder.UpdateConfigurationWithReplace(configuration);

            LoggingSection           = GetSection(LoggingSettings.SectionName, configuration);
            ExceptionHandlingSection = GetSection(ExceptionHandlingSettings.SectionName, configuration);
        }
Beispiel #20
0
        static void LogWithFluentInterface(CustomLogEntry logEntry)
        {
            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureData()
                .ForDatabaseNamed("Logging")
                    .ThatIs.ASqlDatabase()
                    .WithConnectionString(@"data source=.\SQLEXPRESS;Integrated Security=SSPI;Database=Logging")
                .AsDefault();

            builder.ConfigureLogging()
                    .WithOptions
                        .DoNotRevertImpersonation()
                    .LogToCategoryNamed("General")
                        .WithOptions.SetAsDefaultCategory()
                        .SendTo.CustomDatabase("Custom Database Trace Listener")
                        .WithAddCategoryStoredProcedure("AddCategory")
                        .UseDatabase("Logging")
                        .Filter(System.Diagnostics.SourceLevels.All)
                        .WithWriteLogStoredProcedure("WriteLog")
                        .FormatWithSharedFormatter("Text Formatter")
                    .SpecialSources.LoggingErrorsAndWarningsCategory
                        .SendTo.EventLog("Event Log Listener")
                        .FormatWith(new FormatterBuilder()
                             .TextFormatterNamed("Text Formatter")
                               .UsingTemplate(@"Timestamp: {timestamp}{newline}
            Message: {message}{newline}
            Category: {category}{newline}
            Priority: {priority}{newline}
            EventId: {eventid}{newline}
            Severity: {severity}{newline}
            Title:{title}{newline}
            Machine: {localMachine}{newline}
            App Domain: {localAppDomain}{newline}
            ProcessId: {localProcessId}{newline}
            Process Name: {localProcessName}{newline}
            Thread Name: {threadName}{newline}
            Win32 ThreadId:{win32ThreadId}{newline}
            Extended Properties: {dictionary({key} - {value}{newline})}"))
                            .ToLog("Application")
                            .ToMachine(".")
                            .UsingEventLogSource("Enterprise Library Logging")
                            .Filter(SourceLevels.All)
                            ;

            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);

            var dbProviderFactory = new DatabaseProviderFactory(configSource);
            DatabaseFactory.SetDatabaseProviderFactory(dbProviderFactory, false);

            var logWriterFactory = new LogWriterFactory(configSource);
            var logWriter = logWriterFactory.Create();
            logWriter.Write(logEntry);

            // Re-initialize static Logger
            Logger.SetLogWriter(logWriter, false);
            Logger.Write("Test2", "General");
        }
Beispiel #21
0
        public TestConfigurationBuilder AddLoggingSettings()
        {
            builder.ConfigureLogging()
            .WithOptions.FilterOnPriority("PriorityFilter")
            .StartingWithPriority(10)
            .UpToPriority(20)
            .LogToCategoryNamed("General")
            .SendTo.EventLog("EventLogListener")
            .ToLog("Application");

            return(this);
        }
        static internal void ClearLog()
        {
            string originalFileName = string.Format(@"C:\Logs\LogFileClearance.log");
            string tempFileName     = originalFileName.Replace(".log", "(TEMP).log");
            var    textFormatter    = new FormatterBuilder()
                                      .TextFormatterNamed("Custom Timestamped Text Formatter")
                                      .UsingTemplate("{timestamp(local:MM/dd/yy hh:mm:ss.fff tt)} tid={win32ThreadId}: {message}");

            #region Set the Logging LogWriter to use the temp file
            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
            .LogToCategoryNamed(INFO_CATEGORY).WithOptions.SetAsDefaultCategory()
            .SendTo.FlatFile("Flat File Trace Listener")
            .ToFile(tempFileName);

            using (DictionaryConfigurationSource configSource = new DictionaryConfigurationSource())
            {
                builder.UpdateConfigurationWithReplace(configSource);
                Marker.customLogWriter = new LogWriterFactory(configSource).Create();
            }
            InitializeLogger();
            #endregion

            #region Clear the original log file
            if (File.Exists(originalFileName))
            {
                File.WriteAllText(originalFileName, string.Empty);
            }
            #endregion

            #region Re-connect the original file to the log writer
            builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
            .WithOptions.DoNotRevertImpersonation()
            .LogToCategoryNamed(INFO_CATEGORY).WithOptions.SetAsDefaultCategory()
            .SendTo.RollingFile("Rolling Flat File Trace Listener")
            .RollAfterSize(1000)
            .FormatWith(textFormatter).WithHeader("").WithFooter("")
            .ToFile(originalFileName);

            using (DictionaryConfigurationSource configSource = new DictionaryConfigurationSource())
            {
                builder.UpdateConfigurationWithReplace(configSource);
                Marker.customLogWriter = new LogWriterFactory(configSource).Create();
            }
            InitializeLogger();
            #endregion
        }
        protected override void Arrange()
        {
            base.Arrange();

            var sourceBuilder = new ConfigurationSourceBuilder();

            sourceBuilder.ConfigureLogging()
                    .LogToCategoryNamed("General")
                        .SendTo.EventLog("eventlog listener")
                                    .ToLog("Application")
                    .LogToCategoryNamed("ArithmicExceptions")
                        .SendTo.SharedListenerNamed("eventlog listener");

            sourceBuilder.UpdateConfigurationWithReplace(Source);
            
            LogginSettings = (LoggingSettings)Source.GetSection(LoggingSettings.SectionName);
        }
        protected override void Arrange()
        {
            base.Arrange();

            var sourceBuilder = new ConfigurationSourceBuilder();

            sourceBuilder.ConfigureLogging()
            .LogToCategoryNamed("General")
            .SendTo.EventLog("eventlog listener")
            .ToLog("Application")
            .LogToCategoryNamed("ArithmicExceptions")
            .SendTo.SharedListenerNamed("eventlog listener");

            sourceBuilder.UpdateConfigurationWithReplace(Source);

            LogginSettings = (LoggingSettings)Source.GetSection(LoggingSettings.SectionName);
        }
Beispiel #25
0
        static Log()
        {
            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
                   .LogToCategoryNamed("General")
                     .WithOptions.SetAsDefaultCategory()
                     .SendTo.FlatFile("Log File")
                       .FormatWith(new FormatterBuilder()
                         .TextFormatterNamed("Text Formatter")
                           .UsingTemplate("{message}{newline}"))
                         .ToFile("AppLog.txt");

            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);
            EnterpriseLibraryContainer.Current
              = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
        }
        protected override void Arrange()
        {
            base.Arrange();

            ConfigurationSourceBuilder sourceBuilder = new ConfigurationSourceBuilder();
            sourceBuilder.ConfigureLogging().LogToCategoryNamed("General").SendTo.EventLog("Listener").SendTo.Msmq("msmqListener");

            DesignDictionaryConfigurationSource source = new DesignDictionaryConfigurationSource();
            sourceBuilder.UpdateConfigurationWithReplace(source);

            var applicationModel = Container.Resolve<ApplicationViewModel>();
            var sourceModel = applicationModel.CurrentConfigurationSource;

            sourceModel.Load(source);
            foreach (var element in sourceModel.Sections.SelectMany(x => x.DescendentElements())) element.InheritedFromParentConfiguration = false;

            applicationModel.NewEnvironment();
            Environment = applicationModel.Environments.First();

            LoggingSectionViewModel = sourceModel.Sections.Where(x => x.SectionName == LoggingSettings.SectionName).First();
        }
        protected override void Arrange()
        {
            base.Arrange();

            var resourceHelper = new ResourceHelper <ConfigFileLocator>();

            resourceHelper.DumpResourceFileToDisk(MainConfigurationFile);
            resourceHelper.DumpResourceFileToDisk(SatelliteConfigurationFile);

            var configurationSourceSection = ConfigurationSource.Sections.Where(s => s.ConfigurationType == typeof(ConfigurationSourceSection)).Single();

            configurationSourceSection.Property("SelectedSource").Value = SatelliteSourceName;

            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
            .LogToCategoryNamed("General")
            .SendTo.EventLog("EventLogListener")
            .ToLog("Application")
            .FormatWith(new FormatterBuilder().TextFormatterNamed("TextFormatter"));
            var section = builder.Get(LoggingSettings.SectionName);

            ConfigurationSource.AddSection(LoggingSettings.SectionName, section);
        }
 protected override void Arrange()
 {
     ConfigurationSourceBuilder = new ConfigurationSourceBuilder();
     ConfigureLogging           = ConfigurationSourceBuilder.ConfigureLogging();
     CategorySourceBuilder      = ConfigureLogging.LogToCategoryNamed(categoryName);
 }
 protected override void Arrange()
 {
     ConfigurationSourceBuilder = new ConfigurationSourceBuilder();
     ConfigureLogging = ConfigurationSourceBuilder.ConfigureLogging();
     CategorySourceBuilder = ConfigureLogging.LogToCategoryNamed(categoryName);
 }
        protected override void Arrange()
        {
            base.Arrange();

            var resourceHelper = new ResourceHelper<ConfigFileLocator>();
            resourceHelper.DumpResourceFileToDisk(MainConfigurationFile);
            resourceHelper.DumpResourceFileToDisk(SatelliteConfigurationFile);

            var configurationSourceSection = ConfigurationSource.Sections.Where(s => s.ConfigurationType == typeof(ConfigurationSourceSection)).Single();
            configurationSourceSection.Property("SelectedSource").Value = SatelliteSourceName;

            var builder = new ConfigurationSourceBuilder();
            builder.ConfigureLogging()
                .LogToCategoryNamed("General")
                .SendTo.EventLog("EventLogListener")
                .ToLog("Application")
                .FormatWith(new FormatterBuilder().TextFormatterNamed("TextFormatter"));
            var section = builder.Get(LoggingSettings.SectionName);
            ConfigurationSource.AddSection(LoggingSettings.SectionName, section);
        }
        public void BuildsLoggingExceptionHandlerWithFluentConfiguration()
        {
            DictionaryConfigurationSource configSource = new DictionaryConfigurationSource();

            ConfigurationSourceBuilder builder = new ConfigurationSourceBuilder();

            builder.ConfigureExceptionHandling()
            .GivenPolicyWithName("Logging Policy")
            .ForExceptionType(typeof(DivideByZeroException))
            .LogToCategory("Sample Category")
            .UsingEventId(100)
            .UsingExceptionFormatter(typeof(TextExceptionFormatter))
            .UsingTitle("Sample Title")
            .WithPriority(4)
            .WithSeverity(TraceEventType.Transfer)
            .ThenDoNothing();

            builder.ConfigureLogging()
            .LogToCategoryNamed("Sample Category")
            .WithOptions
            .SetAsDefaultCategory()
            .ToSourceLevels(SourceLevels.All)
            .SendTo
            .EventLog("Default Listener")
            .UsingEventLogSource("ExceptionHandling.Bvt.Tests - Fluent")
            .FormatWith(
                new FormatterBuilder()
                .TextFormatterNamed("Default Text Formatter")
                .UsingTemplate("{message}"));

            builder.UpdateConfigurationWithReplace(configSource);

            ExceptionHandlingSettings settings = configSource.GetSection(ExceptionHandlingSettings.SectionName) as ExceptionHandlingSettings;

            Assert.IsNotNull(settings);
            Assert.AreEqual(1, settings.ExceptionPolicies.Count);
            var policy = settings.ExceptionPolicies.Get("Logging Policy");

            Assert.IsNotNull(policy);
            Assert.AreEqual(1, policy.ExceptionTypes.Count);
            var configuredException = policy.ExceptionTypes.Get(0);

            Assert.AreEqual(typeof(DivideByZeroException), configuredException.Type);
            Assert.AreEqual(PostHandlingAction.None, configuredException.PostHandlingAction);
            Assert.AreEqual(1, configuredException.ExceptionHandlers.Count);

            var handler = configuredException.ExceptionHandlers.Get(0) as LoggingExceptionHandlerData;

            Assert.IsNotNull(handler);
            Assert.AreEqual("Sample Category", handler.LogCategory);
            Assert.AreEqual(4, handler.Priority);
            Assert.AreEqual(TraceEventType.Transfer, handler.Severity);
            Assert.AreEqual("Sample Title", handler.Title);
            Assert.AreEqual(100, handler.EventId);
            Assert.AreEqual(typeof(TextExceptionFormatter), handler.FormatterType);

            var factory = new LogWriterFactory((e) => configSource.GetSection(e));

            Logger.SetLogWriter(factory.Create());
            var exceptionManager = settings.BuildExceptionManager();
            var exceptionTothrow = new DivideByZeroException("error message");

            exceptionManager.HandleException(exceptionTothrow, "Logging Policy");
            var entry = EventLogEntries.Last;

            Assert.IsTrue(entry.Message.Contains("Type : " + exceptionTothrow.GetType().FullName));
            Assert.IsTrue(entry.Message.Contains("Message : error message"));
        }
Beispiel #32
0
        private void ConfigureEntLib()
        {
            var builder = new ConfigurationSourceBuilder();

            #region Logger
            builder.ConfigureLogging()
            .WithOptions
            .SpecialSources.AllEventsCategory
            .SendTo
            .RollingFile("AllEvent Listener")
            .WithHeader(string.Empty)
            .WithFooter(string.Empty)
            .FormatWithSharedFormatter("Text Formatter")
            .ToFile("%appdata%\\KSYSLOG\\All\\KSYS_all.log")
            .RollAfterSize(10000)
            .CleanUpArchivedFilesWhenMoreThan(5)
            .SendTo
            .Custom <Log.DebuggerTraceListener>("vs debug output")
            .FormatWith(new FormatterBuilder()
                        .TextFormatterNamed("Text Formatter")
                        .UsingTemplate("{timestamp(local:yyyy-MM-dd HH:mm:ss.fff)} {win32ThreadId}{tab}{category}{tab}{severity}{tab}{title}{tab}{message}{tab}{threadName}{tab}{property(ActivityId)}{tab}{dictionary([{key} : {value}])}"))
            .LogToCategoryNamed("Notification.Server")
            .SendTo
            .RollingFile("Information Listener")
            .LogToCategoryNamed("Information")
            .SendTo
            .RollingFile("Informaiton Listener")
            .WithHeader(string.Empty)
            .WithFooter(string.Empty)
            .FormatWithSharedFormatter("Text Formatter")
            .ToFile("%appdata%\\Information\\KSYS_information.log")
            .RollAfterSize(10000)
            .CleanUpArchivedFilesWhenMoreThan(5)
            .LogToCategoryNamed("Debug")
            .SendTo
            .RollingFile("Debug Listener")
            .WithHeader(string.Empty)
            .WithFooter(string.Empty)
            .FormatWithSharedFormatter("Text Formatter")
            .ToFile("%appdata%\\Debug\\KSYS_debug.log")
            .RollAfterSize(10000)
            .CleanUpArchivedFilesWhenMoreThan(5)
            .LogToCategoryNamed("Performance")
            .SendTo
            .RollingFile("Performance Listener")
            .WithHeader(string.Empty)
            .WithFooter(string.Empty)
            .FormatWithSharedFormatter("Text Formatter")
            .ToFile("%appdata%\\Performance\\KSYS_performance.log")
            .RollAfterSize(10000)
            .CleanUpArchivedFilesWhenMoreThan(5)
            .LogToCategoryNamed("Security")
            .SendTo
            .RollingFile("Security Listener")
            .WithHeader(string.Empty)
            .WithFooter(string.Empty)
            .FormatWithSharedFormatter("Text Formatter")
            .ToFile("%appdata%\\Security\\KSYS_security.log")
            .RollAfterSize(10000)
            .CleanUpArchivedFilesWhenMoreThan(5)
            .LogToCategoryNamed("Exception")
            .SendTo
            .RollingFile("Exception Listener")
            .WithHeader(string.Empty)
            .WithFooter(string.Empty)
            .FormatWithSharedFormatter("Text Formatter")
            .ToFile("%appdata%\\Exception\\KSYS_exception.log")
            .RollAfterSize(10000)
            .CleanUpArchivedFilesWhenMoreThan(5)
            ;

            #endregion
            //Exception handling
            builder.ConfigureExceptionHandling()
            .GivenPolicyWithName(ExceptionPolicyName.TaskManagerPolicy)
            .ForExceptionType <System.Exception>().LogToCategory("Exception")
            .ThenDoNothing();
            ;


            //builder.ConfigureExceptionHandling()
            //       .GivenPolicyWithName(ExceptionPolicyName.TaskManagerPolicy)
            //           .ForExceptionType<System.TimeoutException>()
            //             .HandleCustom<SystemTimeoutExceptionHandler>()
            //             .LogToCategory("General")
            //               .WithSeverity(System.Diagnostics.TraceEventType.Error)
            //               .UsingEventId(9000)
            //             .ThenDoNothing()
            //           .ForExceptionType<DataServiceTransportException>()
            //             .HandleCustom<DataServiceTransportExceptionHandler>()
            //             .LogToCategory("General")
            //               .WithSeverity(System.Diagnostics.TraceEventType.Error)
            //               .UsingEventId(9000)
            //             .ThenDoNothing()
            //           .ForExceptionType<Exception>()
            //             .HandleCustom<GeneralExceptionHandler>()
            //             .LogToCategory("General")
            //               .WithSeverity(System.Diagnostics.TraceEventType.Error)
            //               .UsingEventId(9003)
            //             .ThenThrowNewException()
            //           ;


            #region ConfigSource
            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);

            Logger.SetLogWriter(new LogWriterFactory(configSource).Create());
            Log.Log.Debug(TraceEventType.Information, "ConfigureEntLib", "Log manager is started.");

            ExceptionPolicy.SetExceptionManager(new ExceptionPolicyFactory(configSource).CreateManager());
            Log.Log.Debug(TraceEventType.Information, "ConfigureEntLib", "Exception manager is started.");
            #endregion
        }
Beispiel #33
0
        protected override void Arrange()
        {
            base.Arrange();

            ConfigurationSourceBuilder.ConfigureLogging();
        }
Beispiel #34
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationSourceBuilder();
            builder.ConfigureLogging()
                .WithOptions.FilterOnPriority("aaa").UpToPriority(10)
                // 名前を付けてログの定義を開始
                .LogToCategoryNamed("General")
                    // WithOptionsで追加オプション
                    // ここではGeneralをデフォルトのカテゴリとして設定
                    .WithOptions.SetAsDefaultCategory()
                    // フラットファイルに出力ファイル名はdefault.log
                    .SendTo.FlatFile("FlatFileListener").ToFile("default.log")
                    // フィルタリング(警告以上を表示する)
                    .Filter(SourceLevels.Warning)
                    // ログのフォーマットを指定
                    .FormatWith(new FormatterBuilder()
                        // フォーマッタの名前を指定
                        .TextFormatterNamed("LogFormatter")
                        // フォーマットを指定
                        .UsingTemplate("{timestamp(local:yyyy/MM/dd HH:mm:ss.fff)}:  {severity}: {message}"))
                // Rollingという名前でログの定義を開始
                .LogToCategoryNamed("Rolling")
                    // SendTo.RollingFileで一定の条件を満たしたらローリング
                    .SendTo.RollingFile("RollingFileListener")
                        // 1000KBでローリング
                        .RollAfterSize(1000)
                        // 1分間隔でローリング
                        .RollEvery(RollInterval.Minute)
                        // ローリングしたファイルにタイムスタンプをつける
                        .UseTimeStampPattern("yyyyMMddHHmmssfff")
                        // 10世代管理
                        .CleanUpArchivedFilesWhenMoreThan(10)
                        // ファイル名はrolling.log
                        .ToFile("rolling.log")
                // EventLogという名前でログの定義を開始
                .LogToCategoryNamed("EventLog")
                    // EventLogに送信するEventLogListener
                    .SendTo.EventLog("EventLogListener")
                    // ソースはApplication
                    .UsingEventLogSource("Application");

            EnterpriseLibraryContainer.Current = builder.CreateContainer();

            var l = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
            // Verbose~Criticalまでのログを出力
            l.Write(new LogEntry { Message = "VerboseMessage", Severity = TraceEventType.Verbose});
            l.Write(new LogEntry { Message = "InformationMessage", Severity = TraceEventType.Information});
            l.Write(new LogEntry { Message = "WarningMessage", Severity = TraceEventType.Warning});
            l.Write(new LogEntry { Message = "ErrorMessage", Severity = TraceEventType.Error});
            l.Write(new LogEntry { Message = "CriticalMessage", Severity = TraceEventType.Critical});

            Process.Start("default.log");

            foreach (var i in Enumerable.Range(1, 100000))
            {
                l.Write("ログメッセージ", "Rolling");
                l.Write(new LogEntry { Message = "sample message", Categories = { "Rolling" } });
            }

            l.Write("EventLogMessage", "EventLog", 0, 0, TraceEventType.Information);
        }
Beispiel #35
0
        public static void Initialise()
        {
            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
            .WithOptions
            .DoNotRevertImpersonation()
            .LogToCategoryNamed("General")
            .WithOptions
            .SetAsDefaultCategory()
            .SendTo
            .RollingFile("Rolling Flat File Trace Listener")
            .ToFile(@"log\trace.log")
            .WithHeader("----------------------")
            .RollAfterSize(50)
            .UseTimeStampPattern("MM_dd_yyyy")
            .WhenRollFileExists(RollFileExistsBehavior.Increment)
            .RollEvery(RollInterval.Day)
            .WithTraceOptions(TraceOptions.Callstack | TraceOptions.DateTime | TraceOptions.LogicalOperationStack | TraceOptions.ProcessId | TraceOptions.ThreadId | TraceOptions.Timestamp)
            .CleanUpArchivedFilesWhenMoreThan(5);

            var exceptionhandling = builder.ConfigureExceptionHandling();

            //exceptionhandling
            //    .GivenPolicyWithName("PassThroughPolicy")
            //    .ForExceptionType<System.Exception>()
            //        .ReplaceWith<PassThroughException>()
            //        .ThenNotifyRethrow();

            //exceptionhandling
            //    .GivenPolicyWithName("BusinessLogicPolicy")
            //    .ForExceptionType<System.Exception>()
            //        .LogToCategory("General")
            //            .WithSeverity(System.Diagnostics.TraceEventType.Error)
            //            .WithPriority(0)
            //            .UsingEventId(100)
            //        .ReplaceWith<UserInterfaceException>()
            //            .UsingMessage("A User Interface Error Happened.")
            //        .ThenThrowNewException();

            exceptionhandling
            .GivenPolicyWithName("UserInterfacePolicy")
            .ForExceptionType <System.Exception>()
            .LogToCategory("General")
            .WithSeverity(System.Diagnostics.TraceEventType.Error)
            .WithPriority(0)
            .UsingEventId(100)
            .ReplaceWith <UserInterfaceException>()
            .UsingMessage("A User Interface Error Happened.")

            //Werner: Removed this so that it shows the Dialogue and restarts the system (2014-10-20)
            //.ThenThrowNewException()
            ;



            /*
             *
             * ConfigurationSourceBuilder formatBuilder = new ConfigurationSourceBuilder();
             *
             * ConfigurationSourceBuilder builder = new ConfigurationSourceBuilder();
             * builder.ConfigureLogging().LogToCategoryNamed("General").
             *  SendTo.
             *  RollingFile("Rolling Flat File Trace Listener")
             *  .CleanUpArchivedFilesWhenMoreThan(2).WhenRollFileExists(RollFileExistsBehavior.Increment)
             *  .WithTraceOptions(TraceOptions.None)
             *  .RollEvery(RollInterval.Minute)
             *  .RollAfterSize(10)
             *  .UseTimeStampPattern("yyyy-MM-dd")
             *  .ToFile("log\trace.log")
             *  .FormatWith(new FormatterBuilder().TextFormatterNamed("textFormatter"));
             */

            var configSource = new DictionaryConfigurationSource();

            builder.UpdateConfigurationWithReplace(configSource);
            EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

            /*
             * var writer = EnterpriseLibraryContainer.Current.GetInstance<Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter>();
             *
             * DateTime stopWritingTime = DateTime.Now.AddMinutes(10);
             * while (DateTime.Now < stopWritingTime)
             * {
             *  writer.Write("test", "General");
             * }
             */
        }
Beispiel #36
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
            .WithOptions.FilterOnPriority("aaa").UpToPriority(10)
            // 名前を付けてログの定義を開始
            .LogToCategoryNamed("General")
            // WithOptionsで追加オプション
            // ここではGeneralをデフォルトのカテゴリとして設定
            .WithOptions.SetAsDefaultCategory()
            // フラットファイルに出力ファイル名はdefault.log
            .SendTo.FlatFile("FlatFileListener").ToFile("default.log")
            // フィルタリング(警告以上を表示する)
            .Filter(SourceLevels.Warning)
            // ログのフォーマットを指定
            .FormatWith(new FormatterBuilder()
                        // フォーマッタの名前を指定
                        .TextFormatterNamed("LogFormatter")
                        // フォーマットを指定
                        .UsingTemplate("{timestamp(local:yyyy/MM/dd HH:mm:ss.fff)}:  {severity}: {message}"))
            // Rollingという名前でログの定義を開始
            .LogToCategoryNamed("Rolling")
            // SendTo.RollingFileで一定の条件を満たしたらローリング
            .SendTo.RollingFile("RollingFileListener")
            // 1000KBでローリング
            .RollAfterSize(1000)
            // 1分間隔でローリング
            .RollEvery(RollInterval.Minute)
            // ローリングしたファイルにタイムスタンプをつける
            .UseTimeStampPattern("yyyyMMddHHmmssfff")
            // 10世代管理
            .CleanUpArchivedFilesWhenMoreThan(10)
            // ファイル名はrolling.log
            .ToFile("rolling.log")
            // EventLogという名前でログの定義を開始
            .LogToCategoryNamed("EventLog")
            // EventLogに送信するEventLogListener
            .SendTo.EventLog("EventLogListener")
            // ソースはApplication
            .UsingEventLogSource("Application");


            EnterpriseLibraryContainer.Current = builder.CreateContainer();

            var l = EnterpriseLibraryContainer.Current.GetInstance <LogWriter>();

            // Verbose~Criticalまでのログを出力
            l.Write(new LogEntry {
                Message = "VerboseMessage", Severity = TraceEventType.Verbose
            });
            l.Write(new LogEntry {
                Message = "InformationMessage", Severity = TraceEventType.Information
            });
            l.Write(new LogEntry {
                Message = "WarningMessage", Severity = TraceEventType.Warning
            });
            l.Write(new LogEntry {
                Message = "ErrorMessage", Severity = TraceEventType.Error
            });
            l.Write(new LogEntry {
                Message = "CriticalMessage", Severity = TraceEventType.Critical
            });

            Process.Start("default.log");

            foreach (var i in Enumerable.Range(1, 100000))
            {
                l.Write("ログメッセージ", "Rolling");
                l.Write(new LogEntry {
                    Message = "sample message", Categories = { "Rolling" }
                });
            }

            l.Write("EventLogMessage", "EventLog", 0, 0, TraceEventType.Information);
        }