コード例 #1
0
        public void AddsLogSourceToCollection()
        {
            var config = new LoggingConfiguration();
            config.AddLogSource("mock", new MockTraceListener());

            Assert.AreEqual<int>(1, config.LogSources["mock"].Listeners.Count);
        }
コード例 #2
0
ファイル: RobotProgram.cs プロジェクト: ItzWarty/MonoGameTest
        private static void InitializeLogging()
        {
            var config = new LoggingConfiguration();
             Target debuggerTarget = new DebuggerTarget() {
            Layout = "${longdate}|${level}|${logger}|${message} ${exception:format=tostring}"
             };
             Target consoleTarget = new ColoredConsoleTarget() {
            Layout = "${longdate}|${level}|${logger}|${message} ${exception:format=tostring}"
             };

            #if !DEBUG
             debuggerTarget = new AsyncTargetWrapper(debuggerTarget);
             consoleTarget = new AsyncTargetWrapper(consoleTarget);
            #else
             AsyncTargetWrapper a; // Placeholder for optimizing imports
            #endif

             config.AddTarget("debugger", debuggerTarget);
             config.AddTarget("console", consoleTarget);

             var debuggerRule = new LoggingRule("*", LogLevel.Trace, debuggerTarget);
             config.LoggingRules.Add(debuggerRule);

             var consoleRule = new LoggingRule("*", LogLevel.Trace, consoleTarget);
             config.LoggingRules.Add(consoleRule);

             LogManager.Configuration = config;
        }
コード例 #3
0
        public Logger(string name, LoggingConfiguration config)
        {
            Name = name;

            // add a target...
            _configuration = config;
        }
コード例 #4
0
        public virtual LoggingConfiguration CreateDefaultSettings()
        {
            // default logging config...
            var configuration = new LoggingConfiguration();
            configuration.AddTarget(LogLevel.Trace, LogLevel.Fatal, new EtwTarget());

            return configuration;
        }
コード例 #5
0
        public void SpecialLogSourcesAreNotNull()
        {
            var config = new LoggingConfiguration();

            Assert.IsNotNull(config.SpecialSources.AllEvents);
            Assert.IsNotNull(config.SpecialSources.LoggingErrorsAndWarnings);
            Assert.IsNotNull(config.SpecialSources.Unprocessed);
        }
コード例 #6
0
ファイル: LoggerTests.cs プロジェクト: onovotny/MetroLog
 static Tuple<Logger, TestTarget> CreateTarget()
 {
     var testTarget = new TestTarget();
     var config = new LoggingConfiguration();
     config.AddTarget(LogLevel.Trace, LogLevel.Fatal, testTarget);
     
     return Tuple.Create(new Logger("Foobar", config), testTarget);
 }
コード例 #7
0
        public static void ConfigureForConsoleLogging(LogLevel minLevel)
        {
            ConsoleTarget consoleTarget = new ConsoleTarget();

            LoggingConfiguration config = new LoggingConfiguration();
            LoggingRule rule = new LoggingRule("*", minLevel, consoleTarget);
            config.LoggingRules.Add(rule);
            LogManager.Configuration = config;
        }
コード例 #8
0
ファイル: LevelTests.cs プロジェクト: onovotny/MetroLog
        Tuple<ILogManager, TestTarget> CreateWithLevel(LogLevel min, LogLevel max)
        {
            var testTarget = new TestTarget();

            var config = new LoggingConfiguration();
            config.AddTarget(min, max, testTarget);

            return Tuple.Create<ILogManager, TestTarget>(new LogManager(config), testTarget);
        }
コード例 #9
0
        public void SetIsLogginEnabledToValseAddsFilter()
        {
            var config = new LoggingConfiguration();

            Assert.IsTrue(config.IsLoggingEnabled);

            config.IsLoggingEnabled = false;

            Assert.IsFalse(config.IsLoggingEnabled);

            Assert.AreEqual<int>(1, config.Filters.OfType<LogEnabledFilter>().Count());
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: hispafox/LibLog
        private static void Main(string[] args)
        {
            var config = new LoggingConfiguration();
            var consoleTarget = new ColoredConsoleTarget();
            config.AddTarget("console", consoleTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget));
            LogManager.Configuration = config;

            Foo.Bar();

            Console.ReadLine();
        }
コード例 #11
0
ファイル: LoggerTests.cs プロジェクト: mqmanpsy/MetroLog
        private static Tuple<ILoggerAsync, TestTarget> CreateTarget()
        {
            var testTarget = new TestTarget();
            var config = new LoggingConfiguration();
            config.AddTarget(LogLevel.Trace, LogLevel.Fatal, testTarget);

            var type = Type.GetType("MetroLog.Internal.Logger, MetroLog");

            var ctor = type.GetConstructors().First();

            var created = ctor.Invoke(new object[]{"Foobar", config});
            return Tuple.Create((ILoggerAsync)created, testTarget);
        }
コード例 #12
0
ファイル: NLogLoggerTest.cs プロジェクト: kjniemi/ignite
        public void SetUp()
        {
            var cfg = new LoggingConfiguration();

            _logTarget = new MemoryTarget("mem")
            {
                Layout = new SimpleLayout("${Logger}|${Level}|${Message}|${exception}|${all-event-properties}")
            };

            cfg.AddTarget(_logTarget);

            cfg.AddRule(global::NLog.LogLevel.Trace, global::NLog.LogLevel.Error, _logTarget);

            LogManager.Configuration = cfg;
        }
コード例 #13
0
ファイル: NLogFactory.cs プロジェクト: zivraf/SenseNet
        /// <summary>
        /// Updates a logging configuration for Azure compatability 
        /// </summary>
        /// <param name="config"></param>
        public static void UpdateConfigForCloud(LoggingConfiguration config)
        {
            // Set up the azure role name variables
            // Add Azure role infomration to log4net properties
            var role = ConfigurationHelper.RoleName;
            var instance = ConfigurationHelper.InstanceName;

            // Update the file targets with the proper log storage directory base
            foreach (var ft in config.AllTargets.OfType<FileTarget>())
            {
                var name = ft.Name.Replace("_wrapped", "");

                // With Azure SDK 2.5 we can use absolute paths, not relative paths
                //var archiveFileName = String.Format("{0}Log_{1}_{2}_{3}_{{#####}}",
                //    name, role, instance, @"${shortdate}.log");
                //ft.ArchiveFileName = Path.Combine(archiveDirPath, archiveFileName);

                //var fileName = String.Format("{0}Log_{1}_{2}.log",
                //    name, role, instance);
                //ft.FileName = Path.Combine(logDirPath, fileName);

                // Update the file targets with the role instance names for layout
                if (ft.Layout is CsvLayout)
                {
                    var csvLayout = ft.Layout as CsvLayout;
                    var roleCol = csvLayout.Columns.FirstOrDefault(e => e.Name == "role");
                    if (roleCol != null)
                        roleCol.Layout = role;

                    var instanceCol = csvLayout.Columns.FirstOrDefault(e => e.Name == "instance");
                    if (instanceCol != null)
                        instanceCol.Layout = instance;
                }
            }

            // Add the trace listener when running in emulator
            if (RoleEnvironment.IsAvailable && RoleEnvironment.IsEmulated)
            {
                var trace = new global::NLog.Targets.TraceTarget();
                trace.Name = "emulator_trace";
                config.AddTarget("emulator_trace", trace);

                foreach (var rule in config.LoggingRules)
                {
                    rule.Targets.Add(trace);
                }
            }
        }
コード例 #14
0
        public NLogFiltering()
        {
            #region NLogFiltering

            LoggingConfiguration config = new LoggingConfiguration();

            ColoredConsoleTarget target = new ColoredConsoleTarget();
            config.AddTarget("console", target);
            config.LoggingRules.Add(new LoggingRule("MyNamespace.*", LogLevel.Debug, target));

            LogManager.Configuration = config;

            SetLoggingLibrary.NLog();

            #endregion
        }
コード例 #15
0
    public NLogFiltering()
    {
        #region NLogFiltering

        LoggingConfiguration config = new LoggingConfiguration();

        ColoredConsoleTarget target = new ColoredConsoleTarget();
        config.AddTarget("console", target);
        config.LoggingRules.Add(new LoggingRule("MyNamespace.*", LogLevel.Debug, target));

        LogManager.Configuration = config;

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

        #endregion
    }
コード例 #16
0
        public async Task FileStreamingThreadSafe()
        {
            var loggingConfiguration = new LoggingConfiguration();
            loggingConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal, new StreamingFileTarget());
            LogManagerFactory.DefaultConfiguration = loggingConfiguration;
            var log = (ILoggerAsync)LogManagerFactory.DefaultLogManager.GetLogger<FileStreamingTargetTests>();

            var tasks = new List<Task>(100);
            for (int i = 0; i < 100; i++)
            {
                var t = log.TraceAsync("What thread am I?");
                tasks.Add(t);
            }

            await Task.WhenAll(tasks);
        }
コード例 #17
0
        public async Task TestBrokenTarget()
        {
            var testTarget = new TestTarget();

            var config = new LoggingConfiguration();
            config.AddTarget(LogLevel.Trace, LogLevel.Fatal, new BrokenTarget());
            config.AddTarget(LogLevel.Trace, LogLevel.Fatal, testTarget);

            var target = new LogManagerBase(config);

            // this should ignore errors in the broken target and flip down to the working target...
            var logger = (Logger)target.GetLogger("Foobar");
            await logger.TraceAsync("Hello, world.");

            // check...
            Assert.Equal(1, testTarget.NumWritten);
            Assert.Equal(LogLevel.Trace, testTarget.LastWritten.Level);
            Assert.Null(testTarget.LastWritten.Exception);
        }
コード例 #18
0
ファイル: Usage.cs プロジェクト: odelljl/docs.particular.net
    Usage()
    {
        #region NLogInCode

        LoggingConfiguration config = new LoggingConfiguration();

        ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget
        {
            Layout = "${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}"
        };
        config.AddTarget("console", consoleTarget);
        config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget));

        LogManager.Configuration = config;

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

        #endregion
    }
コード例 #19
0
ファイル: Logger.cs プロジェクト: onovotny/MetroLog
        static Logger()
        {
            MaxLevel = LogLevel.Trace;


            _logManager = new Lazy<IWinRTLogManager>(() =>
                {
                    var max = (PclLogLevel)MaxLevel;
                    // Log everything for now
                    var configuration = new LoggingConfiguration();
                    configuration.AddTarget(max, PclLogLevel.Fatal, new DebugTarget());
                    configuration.AddTarget(max, PclLogLevel.Fatal, new EtwTarget());
                    configuration.AddTarget(max, PclLogLevel.Fatal, new EventTarget(OnLogMessageInternal));
                    configuration.AddTarget(max, PclLogLevel.Fatal, new StreamingFileTarget());

                    LogManagerFactory.DefaultConfiguration = configuration;

                    return (IWinRTLogManager)LogManagerFactory.DefaultLogManager;
                });
        }
コード例 #20
0
        public void LoggingIsEnabledByDefault()
        {
            var config = new LoggingConfiguration();

            Assert.IsTrue(config.IsLoggingEnabled);
        }
コード例 #21
0
        public void SharedTraceListener()
        {
            var sharedTraceListener = new DefaultTraceListener();

            var config = new LoggingConfiguration();
            config.AddLogSource("General").AddTraceListener(sharedTraceListener);
            config.AddLogSource("Special", SourceLevels.Critical, true, sharedTraceListener);

            Assert.AreEqual<int>(2, config.LogSources.Count);
            Assert.AreEqual<string>("General", config.LogSources.First().Name);
            Assert.AreEqual<string>("Special", config.LogSources.Last().Name);
        }
コード例 #22
0
        public void CanGetAllTraceListeners()
        {
            var listener1 = new MockTraceListener();
            var listener2 = new MockTraceListener();
            var listener3 = new MockTraceListener();
            var listener4 = new MockTraceListener();

            var config = new LoggingConfiguration();

            config.AddLogSource("source1", listener1, listener2);
            config.AddLogSource("source2", listener2);
            config.AddLogSource("source3", listener1, listener3);
            config.AddLogSource("source4");

            config.SpecialSources.Unprocessed.AddTraceListener(listener2);
            config.SpecialSources.Unprocessed.AddTraceListener(listener4);

            var allListeners = config.AllTraceListeners.ToArray();

            Assert.AreEqual(4, allListeners.Length);
            CollectionAssert.AreEquivalent(new TraceListener[] { listener1, listener2, listener3, listener4 }, allListeners);
        }
コード例 #23
0
        public void DanderTest()
        {
            var config   = new LoggingConfiguration();
            var loglevel = LogLevel.Info;

            var layout = @"${message}";

            var consoleTarget = new ColoredConsoleTarget();

            config.AddTarget("console", consoleTarget);

            consoleTarget.Layout = layout;

            var rule1 = new LoggingRule("*", loglevel, consoleTarget);

            config.LoggingRules.Add(rule1);

            LogManager.Configuration = config;
            var l = LogManager.GetLogger("foo");

            var logs = new List <string>();

            logs.Add(@" D:\Temp\logs\Security_danderspritz_3548.evtx");
            logs.Add(@" D:\Temp\logs\Security_deleted_25733.evtx");
            logs.Add(@" D:\Temp\logs\Security_foxit_danderspritz.evtx");
            logs.Add(@" D:\Temp\logs\Security_original.evtx");
            logs.Add(@" D:\Temp\logs\System2.evtx");


            foreach (var sysLog in logs)
            {
                var total  = 0;
                var total2 = 0;

                l.Error(sysLog + " *******************************************");

                using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read))
                {
                    var es = new EventLog(fs);

                    foreach (var eventRecord in es.GetEventRecords())
                    {
                        l.Info(
                            $"Record #: {eventRecord.RecordNumber} Hidden: {eventRecord.HiddenRecord}, Timestamp: {eventRecord.TimeCreated.ToUniversalTime()} Channel: {eventRecord.Channel} Computer: {eventRecord.Computer} {eventRecord.PayloadData1} {eventRecord.PayloadData2}");


                        //   eventRecord.ConvertPayloadToXml();

                        total += 1;
                    }

                    foreach (var esEventIdMetric in es.EventIdMetrics.OrderBy(t => t.Key))
                    {
                        total2 += esEventIdMetric.Value;
                        l.Info($"{esEventIdMetric.Key}: {esEventIdMetric.Value:N0}");
                    }

                    l.Info($"Total from here: {total:N0}");
                    l.Info($"Total2 from here: {total2:N0}");
                    l.Info($"Event log details: {es}");
                    l.Info($"Event log error count: {es.ErrorRecords.Count:N0}");

                    Check.That(es.ErrorRecords.Count).IsEqualTo(0);
                }
            }
        }
コード例 #24
0
 public static LoggingConfiguration ConfigureNLog(this ILoggerFactory loggerFactory, LoggingConfiguration config)
 {
     ConfigureHiddenAssemblies();
     LogManager.Configuration = config;
     return(config);
 }
コード例 #25
0
        public void ThrowsArgumentNullIfAddLogSourceIsNull()
        {
            MockDisposableTraceListener listener = null;

            var config = new LoggingConfiguration();

            AssertEx.Throws<ArgumentNullException>(() => config.AddLogSource("test", listener));
        }
コード例 #26
0
        /// <summary>
        /// Logs an error.
        /// </summary>
        /// <param name="e">The error to log.</param>
        /// <param name="message">The message to log.</param>
        public static void LogError(Exception e, string message = null)
        {
            _config = _config == null?CreateLogConfig() : _config;

            _logger.Log(LogLevel.Error, e, message);
        }
コード例 #27
0
 /// <summary>
 /// Configures NLog for to log to the specified target so that all messages 
 /// above and including the specified level are output.
 /// </summary>
 /// <param name="target">The target to log all messages to.</param>
 /// <param name="minLevel">The minimal logging level.</param>
 public static void ConfigureForTargetLogging(Target target, LogLevel minLevel)
 {
     LoggingConfiguration config = new LoggingConfiguration();
     LoggingRule rule = new LoggingRule("*", minLevel, target);
     config.LoggingRules.Add(rule);
     LogManager.Configuration = config;
 }
コード例 #28
0
        public static void Main(string[] args)
        {
            LoggingConfiguration.ConfigureLogger("BackendForFrontend");

            CreateWebHostBuilder(args).Build().Run();
        }
コード例 #29
0
        /// <summary>
        /// Logs information.
        /// </summary>
        /// <param name="message">The message to log.</param>
        public static void LogInfo(string message)
        {
            _config = _config == null?CreateLogConfig() : _config;

            _logger.Log(LogLevel.Info, message);
        }
コード例 #30
0
 public void Setup()
 {
     configuration = LoadLoggingConfiguration("LoggingConfiguration");
 }
コード例 #31
0
 /// <summary>
 /// Create a new instance of <see cref="AspectCoreLogServiceProvider"/>
 /// </summary>
 /// <param name="provider"></param>
 /// <param name="loggingConfiguration"></param>
 public AspectCoreLogServiceProvider(IServiceResolver provider, LoggingConfiguration loggingConfiguration)
 {
     _provider = provider ?? throw new ArgumentNullException(nameof(provider));
     _logPayloadClientProviders = _provider.ResolveMany <ILogPayloadClientProvider>() ?? Enumerable.Empty <ILogPayloadClientProvider>();
     _loggingConfiguration      = loggingConfiguration ?? throw new ArgumentNullException(nameof(loggingConfiguration));
 }
コード例 #32
0
ファイル: App.xaml.cs プロジェクト: royben/Resonance
 protected override void OnStartup(StartupEventArgs e)
 {
     base.OnStartup(e);
     LoggingConfiguration.ConfigureLogging();
 }
コード例 #33
0
 public static LoggingConfiguration ConfigureNLog(this ILoggerFactory loggerFactory, LoggingConfiguration config)
 {
     LogManager.AddHiddenAssembly(typeof(NLogLoggerProvider).GetTypeInfo().Assembly);
     LogManager.Configuration = config;
     return(config);
 }
コード例 #34
0
ファイル: Log.cs プロジェクト: st95264/Nitrox
        public static void Setup(bool performanceCritical = false)
        {
            if (logger != null)
            {
                throw new Exception($"{nameof(Log)} setup should only be executed once.");
            }
            logger = LogManager.GetCurrentClassLogger();

            LoggingConfiguration config = new LoggingConfiguration();
            string layout = $@"[${{date:format=HH\:mm\:ss}} {GetLoggerName()}${{event-properties:item={nameof(PlayerName)}}}][${{level:uppercase=true}}] ${{message}} ${{exception}}";

            // Targets where to log to: File and Console
            ColoredConsoleTarget logConsole = new ColoredConsoleTarget(nameof(logConsole))
            {
                Layout = layout,
                DetectConsoleAvailable = false
            };

            logConsole.RowHighlightingRules.Add(new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Error"),
                ForegroundColor = ConsoleOutputColor.Red
            });
            logConsole.RowHighlightingRules.Add(new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Warn"),
                ForegroundColor = ConsoleOutputColor.Yellow
            });
            logConsole.RowHighlightingRules.Add(new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Debug"),
                ForegroundColor = ConsoleOutputColor.DarkGray
            });

            FileTarget logFile = new FileTarget(nameof(logFile))
            {
                FileName                     = $"Nitrox Logs/Nitrox-{GetLoggerName()}.log",
                ArchiveFileName              = $"Nitrox Logs/archives/Nitrox-{GetLoggerName()}.{{#}}.log",
                ArchiveEvery                 = FileArchivePeriod.Day,
                ArchiveNumbering             = ArchiveNumberingMode.Date,
                MaxArchiveFiles              = 7,
                Layout                       = layout,
                EnableArchiveFileCompression = true,
            };
            AsyncTargetWrapper logFileAsync = new AsyncTargetWrapper(logFile, 1000, AsyncTargetWrapperOverflowAction.Grow);

            // Rules for mapping loggers to targets
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logConsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logFileAsync);
            config.AddRuleForOneLevel(LogLevel.Info,
                                      new MethodCallTarget("ingame",
                                                           (evt, obj) =>
            {
                if (InGameLogger == null)
                {
                    return;
                }
                evt.Properties.TryGetValue("game", out object isGameLog);
                if (isGameLog != null && (bool)isGameLog)
                {
                    InGameLogger.Log(evt.FormattedMessage);
                }
            }));

            AddSensitiveFilter(config, target => target is AsyncTargetWrapper || target is FileTarget);

            // Apply config
            LogManager.Configuration = config;
            if (!performanceCritical)
            {
                TimeSource.Current = new AccurateLocalTimeSource();
            }
        }
コード例 #35
0
        // cli entry point:
        static void Main(string[] args)
        {
            // process arguments for logging level
            var argsList = new List <string>(args);

            // setup logger
            // process arguments for hidden debug mode switch
            PyRevitCLILogLevel logLevel = PyRevitCLILogLevel.InfoMessages;
            var config     = new LoggingConfiguration();
            var logconsole = new ConsoleTarget("logconsole")
            {
                Layout = @"${level}: ${message} ${exception}"
            };

            config.AddTarget(logconsole);
            config.AddRule(LogLevel.Error, LogLevel.Fatal, logconsole);

            if (argsList.Contains("--verbose"))
            {
                argsList.Remove("--verbose");
                logLevel = PyRevitCLILogLevel.InfoMessages;
                config.AddRule(LogLevel.Info, LogLevel.Info, logconsole);
            }

            if (argsList.Contains("--debug"))
            {
                argsList.Remove("--debug");
                logLevel = PyRevitCLILogLevel.Debug;
                config.AddRule(LogLevel.Debug, LogLevel.Debug, logconsole);
            }

            // config logger
            LogManager.Configuration = config;

            try {
                // process docopt
                // docopt raises exception if pattern matching fails
                arguments = new Docopt().Apply(UsagePatterns, argsList, exit: false, help: false);

                // print active arguments in debug mode
                if (logLevel == PyRevitCLILogLevel.Debug)
                {
                    PrintArguments(arguments);
                }

                // setup output log
                if (arguments["--log"] != null)
                {
                    var logfile = new FileTarget("logfile")
                    {
                        FileName = arguments["--log"].Value as string
                    };
                    config.AddTarget(logfile);
                    config.AddRuleForAllLevels(logfile);

                    arguments.Remove("--log");

                    // update logger config
                    LogManager.Configuration = config;
                }

                // check if requesting version
                IsVersionMode = arguments["--version"].IsTrue || arguments["-V"].IsTrue;

                // check if requesting help
                IsHelpMode = arguments["--help"].IsTrue || arguments["-h"].IsTrue;

                // check if requesting help with full usage patterns
                IsHelpUsagePatternMode = arguments["--usage"].IsTrue;

                try {
                    // now call methods based on inputs
                    ProcessArguments();

                    // process global error codes
                    ProcessErrorCodes();
                }
                catch (Exception ex) {
                    LogException(ex, logLevel);
                }

                // Flush and close down internal threads and timers
                LogManager.Shutdown();
            }
            catch (Exception ex) {
                // when docopt fails, print help
                logger.Debug("Arg processing failed. | {0}", ex.Message);
                PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Main);
            }
        }
コード例 #36
0
        public async Task <GetSubcategoryPropertyValuesResponse> GetSubcategoryPropertyValues(GetSubcategoryPropertyValuesRequest reqModel, ConnectSetting connectSetting = null, LoggingConfiguration logSetting = null)
        {
            var request = CreateRequest <GetSubcategoryPropertyValuesRequest>(reqModel);

            request.URI = "sellermgmt/seller/propertyvalue";

            var response = await client.PutAsync(request, connectSetting);

            var result = await ProcessResponse <GetSubcategoryPropertyValuesResponse>(response);

            return(result);
        }
コード例 #37
0
 /// <summary>
 /// Create a new instance of <see cref="NancyLoggingServiceProvider"/>
 /// </summary>
 /// <param name="logPayloadClientProviders"></param>
 /// <param name="loggingConfiguration"></param>
 public NancyLoggingServiceProvider(IEnumerable <ILogPayloadClientProvider> logPayloadClientProviders, LoggingConfiguration loggingConfiguration)
 {
     _logPayloadClientProviders = logPayloadClientProviders ?? Enumerable.Empty <ILogPayloadClientProvider>();
     _loggingConfiguration      = loggingConfiguration ?? throw new ArgumentNullException(nameof(loggingConfiguration));
 }
コード例 #38
0
        public async Task <GetSubcategoryStatusForInternationalCountryResponse> GetSubcategoryStatusForInternationalCountry(GetSubcategoryStatusForInternationalCountryRequest reqModel, ConnectSetting connectSetting = null, LoggingConfiguration logSetting = null)
        {
            var request = CreateRequest <GetSubcategoryStatusForInternationalCountryRequest>(reqModel);

            request.URI = "sellermgmt/seller/subcategory/v2";

            var response = await client.PutAsync(request, connectSetting);

            var result = await ProcessResponse <GetSubcategoryStatusForInternationalCountryResponse>(response);

            return(result);
        }
コード例 #39
0
ファイル: NLogTestBase.cs プロジェクト: fabien-chevalley/NLog
 protected string GetDebugLastMessage(string targetName, LoggingConfiguration configuration)
 {
     return(GetDebugTarget(targetName, configuration).LastMessage);
 }
コード例 #40
0
 /// <summary>
 /// 覆盖默认配置文件
 /// </summary>
 public static void OverrideConfiguration(LoggingConfiguration loggingConfiguration)
 {
     NLog.LogManager.Configuration = loggingConfiguration;
 }
コード例 #41
0
        public void CanAddAsynchronousTraceListenerToSpecialSource()
        {
            var listener = new MockTraceListener { Name = "listener", Filter = new EventTypeFilter(SourceLevels.Critical) };

            var config = new LoggingConfiguration();

            config.SpecialSources.LoggingErrorsAndWarnings.AddAsynchronousTraceListener(listener);

            var addedListener = (AsynchronousTraceListenerWrapper)config.SpecialSources.LoggingErrorsAndWarnings.Listeners.First();

            Assert.AreSame(listener, addedListener.TraceListener);
            Assert.AreEqual("listener", addedListener.Name);
            Assert.AreEqual(SourceLevels.Critical, ((EventTypeFilter)addedListener.Filter).EventType);
        }
コード例 #42
0
        public static LoggingConfiguration GetNLogCOnfiguration()
        {
            //%date %-5level [%property{ExecutingCtx}] - %message | %stacktrace{5} | [%logger ]%newline"

            var layout =
                @"${longdate:universalTime=true} ${pad:padding=5:inner=${level:uppercase=true}} [${pad:padding=5:inner=${mdlc:item=IID}}] - ${message} ${when:when=length('${exception}')>0:Inner=[BEGIN_EXCEPTION_}${exception:format=toString,Data:maxInnerExceptionLevel=10}${when:when=length('${exception}')>0:Inner=_END_EXCEPTION]} | ${event-properties:item=EventId_Id} ${ndlc:uppercase=true:separator= => } | [${callsite:fileName=true:methodName=true:cleanNamesOfAsyncContinuations=true:cleanNamesOfAnonymousDelegates=true:includeSourcePath=false}] [${logger:shortName=false}] [$END$]";


            // Step 1. Create configuration object
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            var consoleTarget = new ColoredConsoleTarget();

            config.AddTarget("console", consoleTarget);

            var fileTarget = new FileTarget();

            config.AddTarget("file", fileTarget);


            var commonLayout  = layout;
            var consoleLayout = commonLayout.Replace("[$END$]", "");

            consoleTarget.Layout = consoleLayout;

            fileTarget.FileName = "${basedir}/wwwroot/logs/log.log";

            fileTarget.Layout = commonLayout;


            fileTarget.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
            fileTarget.ArchiveEvery     = FileArchivePeriod.Day;
            //fileTarget.KeepFileOpen = true;
            fileTarget.AutoFlush                    = true;
            fileTarget.ArchiveDateFormat            = "dd-MM-yyyy";
            fileTarget.ArchiveOldFileOnStartup      = true;
            fileTarget.ArchiveFileName              = "${basedir}/wwwroot/logs/log.{#}.log.zip";
            fileTarget.EnableArchiveFileCompression = true;


            var blFileTarget = new FileTarget();

            config.AddTarget("blFileTarget", blFileTarget);


            blFileTarget.FileName = "${basedir}/wwwroot/logs/_bl-log.log";
            blFileTarget.Layout   = fileTarget.Layout;


            blFileTarget.ArchiveNumbering             = ArchiveNumberingMode.DateAndSequence;
            blFileTarget.ArchiveEvery                 = FileArchivePeriod.Day;
            blFileTarget.AutoFlush                    = true;
            blFileTarget.ArchiveDateFormat            = "dd-MM-yyyy";
            blFileTarget.ArchiveOldFileOnStartup      = true;
            blFileTarget.ArchiveFileName              = "${basedir}/wwwroot/logs/_bl-log.{#}.log.zip";
            blFileTarget.EnableArchiveFileCompression = true;


            var blackHole = new NullTarget("blackHole");

            config.AddTarget("blackHole", blackHole);

            // Step 4. Define rules
            var rule1 = new LoggingRule("*", NLog.LogLevel.Debug, consoleTarget);

            config.LoggingRules.Add(rule1);

            var rule2 = new LoggingRule("ES.*", NLog.LogLevel.Debug, fileTarget);

            config.LoggingRules.Add(rule2);
            var rulePH = new LoggingRule("PH.*", NLog.LogLevel.Debug, fileTarget);

            config.LoggingRules.Add(rulePH);


            var ruleMs = new LoggingRule("Microsoft.*", NLog.LogLevel.Trace, blackHole);

            config.LoggingRules.Add(ruleMs);


            var blRule = new LoggingRule("PH.Core3.Test.*", NLog.LogLevel.Debug, blFileTarget);

            blRule.LoggerNamePattern = "PH.Core3.Test.*";

            //config.LoggingRules.Add(blRule);


            var dbg = fileTarget.Layout;


            return(config);
        }
コード例 #43
0
        public void FiltersListIsNotNull()
        {
            var config = new LoggingConfiguration();

            Assert.IsNotNull(config.Filters);
        }
コード例 #44
0
 /// <inheritdoc />
 public NullLogWriter(LoggingConfiguration config) : base(config)
 {
 }
コード例 #45
0
        public void LogSourcesCollectionIsNotNull()
        {
            var config = new LoggingConfiguration();

            Assert.IsNotNull(config.LogSources);
        }
コード例 #46
0
        public static int ExecuteExternalCommandType(Type extCommandType, ref ScriptRuntime runtime)
        {
            // create instance
            object extCommandInstance = Activator.CreateInstance(extCommandType);

            // set properties if available
            // set ExecParams
            var execParams = new ExecParams {
                ExecId           = runtime.ExecId,
                ExecTimeStamp    = runtime.ExecTimestamp,
                ScriptPath       = runtime.ScriptData.ScriptPath,
                ConfigScriptPath = runtime.ScriptData.ConfigScriptPath,
                CommandUniqueId  = runtime.ScriptData.CommandUniqueId,
                CommandControlId = runtime.ScriptData.CommandControlId,
                CommandName      = runtime.ScriptData.CommandName,
                CommandBundle    = runtime.ScriptData.CommandBundle,
                CommandExtension = runtime.ScriptData.CommandExtension,
                HelpSource       = runtime.ScriptData.HelpSource,
                RefreshEngine    = runtime.ScriptRuntimeConfigs.RefreshEngine,
                ConfigMode       = runtime.ScriptRuntimeConfigs.ConfigMode,
                DebugMode        = runtime.ScriptRuntimeConfigs.DebugMode,
                ExecutedFromUI   = runtime.ScriptRuntimeConfigs.ExecutedFromUI,
                UIButton         = runtime.UIControl
            };

            FieldInfo execParamField = null;

            foreach (var fieldInfo in extCommandType.GetFields())
            {
                if (fieldInfo.FieldType == typeof(ExecParams))
                {
                    execParamField = fieldInfo;
                }
            }

            if (execParamField != null)
            {
                execParamField.SetValue(extCommandInstance, execParams);
            }

            // reroute console output to runtime stream
            var          existingOutStream   = Console.Out;
            StreamWriter runtimeOutputStream = new StreamWriter(runtime.OutputStream);
            StreamReader runtimeInputStream  = new StreamReader(runtime.OutputStream);

            runtimeOutputStream.AutoFlush = true;
            Console.SetOut(runtimeOutputStream);
            Console.SetIn(runtimeInputStream);

            // setup logger
            var prevLoggerCfg = LogManager.Configuration;
            var newLoggerCfg  = new LoggingConfiguration();
            var target        = new CLREngineOutputTarget();

            target.CurrentExecParams = execParams;
            target.Name   = logger.Name;
            target.Layout = "${level:uppercase=true}: [${logger}] ${message}";
            newLoggerCfg.AddTarget(target.Name, target);
            newLoggerCfg.AddRuleForAllLevels(target);
            LogManager.Configuration = newLoggerCfg;

            // execute
            string commandMessage = string.Empty;

            extCommandType.InvokeMember(
                "Execute",
                BindingFlags.Default | BindingFlags.InvokeMethod,
                null,
                extCommandInstance,
                new object[] {
                runtime.ScriptRuntimeConfigs.CommandData,
                commandMessage,
                runtime.ScriptRuntimeConfigs.SelectedElements
            }
                );

            // revert logger back to previous
            LogManager.Configuration = prevLoggerCfg;

            // cleanup reference to exec params
            target.CurrentExecParams = null;
            if (execParamField != null)
            {
                execParamField.SetValue(extCommandInstance, null);
            }

            // reroute console output back to original
            Console.SetOut(existingOutStream);
            runtimeOutputStream = null;

            return(ScriptExecutorResultCodes.Succeeded);
        }
コード例 #47
0
        public void DirTestToFix()
        {
            var config   = new LoggingConfiguration();
            var loglevel = LogLevel.Debug;

            var layout = @"${message}";

            var consoleTarget = new ColoredConsoleTarget();

            config.AddTarget("console", consoleTarget);

            consoleTarget.Layout = layout;

            var rule1 = new LoggingRule("*", loglevel, consoleTarget);

            config.LoggingRules.Add(rule1);

            LogManager.Configuration = config;
            var l = LogManager.GetLogger("foo");

            // var sourceDir = @"D:\SynologyDrive\EventLogs\To Fix\Damaged";
            var sourceDir = @"D:\SynologyDrive\EventLogs\To Fix";
            var files     = Directory.GetFiles(sourceDir, "*.evtx").ToList();

            //   var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\To Fix\Template OK","*.evtx").ToList();

            l.Info($"{sourceDir}");

            var total  = 0;
            var total2 = 0;

            foreach (var file in files)
            {
                l.Info(
                    $"\r\n\r\n\r\n-------------------------- file {Path.GetFileName(file)}--------------------------");
                using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    try
                    {
                        var es = new EventLog(fs);

                        foreach (var eventRecord in es.GetEventRecords())
                        //  try
                        {
                            //      l.Info( eventRecord);
                            //l.Info(eventRecord.ConvertPayloadToXml());
                            //eventRecord.ConvertPayloadToXml();
                        }

//                        catch (Exception e)
//                        {
//                           l.Error($"Record: {eventRecord} failed to parse: {e.Message} {e.StackTrace}");
//                        }

                        foreach (var esEventIdMetric in es.EventIdMetrics.OrderBy(t => t.Key))
                        {
                            total2 += esEventIdMetric.Value;
                            l.Info($"{esEventIdMetric.Key}: {esEventIdMetric.Value:N0}");
                        }

                        l.Info($"Total from here: {total:N0}");
                        l.Info($"Total2 from here: {total2:N0}");
                        l.Info($"Event log details: {es}");
                        l.Info($"Event log error count: {es.ErrorRecords.Count:N0}");

                        Check.That(es.ErrorRecords.Count).IsEqualTo(0);
                    }
                    catch (Exception e)
                    {
                        l.Error($"FILE : {file} failed to parse: {e.Message} {e.StackTrace}");
                    }
                }
            }
        }
コード例 #48
0
 /// <summary>
 /// Initializes this instance.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
 {
     this.Initialize(configuration);
 }
コード例 #49
0
 /// <summary>
 /// Create a new instance of <see cref="ExceptionlessPayloadClientProvider"/>.
 /// </summary>
 /// <param name="settings"></param>
 /// <param name="loggingConfiguration"></param>
 public ExceptionlessPayloadClientProvider(IOptions <ExceptionlessSinkOptions> settings, LoggingConfiguration loggingConfiguration)
 {
     _sinkOptions          = settings == null ? new ExceptionlessSinkOptions() : settings.Value;
     _loggingConfiguration = loggingConfiguration ?? throw new ArgumentNullException(nameof(loggingConfiguration));
 }
 protected override void ModifyLoggingConfigurationBeforeCommit(string nameOfTargetForSut, LoggingConfiguration config)
 {
     AddControlOutputToCheckAgainst(nameOfTargetForSut, config);
     base.ModifyLoggingConfigurationBeforeCommit(nameOfTargetForSut, config);
 }
コード例 #51
0
 /// <summary>
 /// Enable NLog as logging provider for Microsoft Extension Logging
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="configuration">New NLog config.</param>
 /// <returns>ILoggingBuilder for chaining</returns>
 public static ILoggingBuilder AddNLog(this ILoggingBuilder builder, LoggingConfiguration configuration)
 {
     return(AddNLog(builder, configuration, null));
 }
コード例 #52
0
 /// <summary>
 /// To disable our logger for other assemblies.
 /// </summary>
 /// <param name="cfg">Configuration of logger</param>
 protected void fixLoggerCfg(LoggingConfiguration cfg)
 {
     fixLoggerCfg(cfg, selfLogger);
 }
コード例 #53
0
ファイル: NLogger.cs プロジェクト: pawan9993811/VerifyUI-2.0
        //class TestLogManager
        //{
        //    // A Logger dispenser for the current configuration (Remember to call Flush on application exit)
        //    public static LogFactory Instance { get { return instance.Value; } }
        //    private static Lazy<LogFactory> instance = new Lazy<LogFactory>(BuildLogFactory);


        //    private static LogFactory BuildLogFactory()
        //    {
        //        // Initialize LogFactory object
        //        LogFactory logFactory = new LogFactory();

        //        // Initialize LogFactory Configuration
        //        LoggingConfiguration config = new LoggingConfiguration();


        //        // Register the custom layout to show stack trace in logs
        //        LayoutRenderer.Register("IndentationLayout", typeof(IndentationLayoutRenderer)); //no space

        //        // Initialize File Target
        //        var fileTarget = new FileTarget("File Target")
        //        {
        //            FileName = "${basedir}/logs/logTest.xml",
        //            DeleteOldFileOnStartup = true, // Deletes old log file every time log is called. Set to true simply for testing purposes
        //            KeepFileOpen = true, // Keeps file open regardless of logger status. (Increases performance)
        //            OpenFileCacheTimeout = 30, // Max number of seconds file is kept open. (Increases performance, but the value will scale with the scope of logger implementation)
        //            Layout = "${IndentationLayout} ${longdate} | ${level:uppercase=true} | ${logger} | ${message} | ${callsite:className=true:fileName=false:includeSourcePath=false:methodName=true}" //use IndentationLayout
        //        };


        //        // Initialize the AsyncWrapper for the fileTarget
        //        AsyncTargetWrapper fileWrapper = new AsyncTargetWrapper();
        //        fileWrapper.WrappedTarget = fileTarget;
        //        fileWrapper.QueueLimit = 5000;  // Limits number of requests in the request queue (Improves performance)
        //        fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; // Blocks incoming requests until request queue if has space

        //        // Initialize the AsyncFlushTargetWrapper for the FileWrapper
        //        AutoFlushTargetWrapper fileFlushWrapper = new AutoFlushTargetWrapper();
        //        fileFlushWrapper.WrappedTarget = fileWrapper;

        //        // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
        //        fileFlushWrapper.Condition = "level >= LogLevel.Info";

        //        // Adding the target to the config
        //        config.AddTarget("file", fileFlushWrapper);

        //        // Creating the Log Level rules for each target and adding them to the config
        //        var fileRule = new LoggingRule("*", fileTarget);
        //        fileRule.EnableLoggingForLevel(exceptionLevel);
        //        fileRule.EnableLoggingForLevels(minLevel, maxLevel);
        //        config.LoggingRules.Add(fileRule);

        //        // Assigning the configuration to the logger
        //        logFactory.Configuration = config;

        //        return logFactory;
        //    }
        //}
        private void SetupLoggingConfiguration()
        {
            // Intialize Config Object
            LoggingConfiguration config = new LoggingConfiguration();

            LayoutRenderer.Register("IndentationLayout", typeof(IndentationLayoutRenderer)); //no space

            /*
             * // Initialize Console Target
             * var consoleTarget = new ColoredConsoleTarget("Console Target")
             * {
             * Layout = @"${time} ${longdate} ${uppercase: ${level}} ${logger} ${message} ${exception: format=ToString}"
             * };
             *
             * // Initialize the AsyncWrapper for the ConsoleTarget
             * AsyncTargetWrapper consoleWrapper = new AsyncTargetWrapper();
             * consoleWrapper.WrappedTarget = consoleTarget;
             * consoleWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block;
             * consoleWrapper.QueueLimit = 5000;
             *
             * // Initialize the AsyncFlushTargetWrapper for the ConsoleWrapper
             * AutoFlushTargetWrapper consoleFlushWrapper = new AutoFlushTargetWrapper();
             * consoleFlushWrapper.WrappedTarget = consoleWrapper;
             *
             * // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
             * consoleFlushWrapper.Condition = "level >= LogLevel.Info";
             *
             * // Adding the target to the config
             * config.AddTarget("console", consoleFlushWrapper);
             */


            // Initialize File Target
            var fileTarget = new FileTarget("File Target")
            {
                FileName = @"${basedir}\logs\Robotics Automation Log.xml",
                DeleteOldFileOnStartup = true,                                                                               // Deletes old log file every time log is called. Set to true simply for testing purposes
                KeepFileOpen           = true,                                                                               // Keeps file open regardless of logger status. (Increases performance)
                OpenFileCacheTimeout   = 30,                                                                                 // Max number of seconds file is kept open. (Increases performance, but the value will scale with the scope of logger implementation)
                Layout = @"${IndentationLayout} ${date:format=yyyy-MM-dd HH\:mm\:ss} | ${level:uppercase=true} | ${message}" //use IndentationLayout
            };

            //// XmlLayout Configuration
            //var XmlLayout = new XmlLayout();



            //XmlLayout.IndentXml = true;
            //XmlLayout.ElementName = "Automated Test";
            //XmlLayout.ElementValue = "Current Test";  // Unit Test name can be entered into here so each log entry will include Unit Test
            //XmlLayout.MaxRecursionLimit = 10;


            //XmlLayout.Attributes.Add(new XmlAttribute("Time", "${longdate}"));
            //XmlLayout.Attributes.Add(new XmlAttribute("Level", "${level:upperCase=true"));
            //XmlLayout.Elements.Add(new XmlElement("Output", "${message}"));
            //XmlLayout.Elements.Add(new XmlElement("Location", "${callsite:methodName=true}"));

            //fileTarget.Layout = XmlLayout;


            // Initialize the AsyncWrapper for the fileTarget
            AsyncTargetWrapper fileWrapper = new AsyncTargetWrapper();

            fileWrapper.WrappedTarget  = fileTarget;
            fileWrapper.QueueLimit     = 5000;                                   // Limits number of requests in the request queue (Improves performance)
            fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; // Blocks incoming requests until request queue if has space

            // Initialize the AsyncFlushTargetWrapper for the FileWrapper
            AutoFlushTargetWrapper fileFlushWrapper = new AutoFlushTargetWrapper();

            fileFlushWrapper.WrappedTarget = fileWrapper;

            /*
             * // Initiliaze Database Target
             * var dbTarget = new DatabaseTarget
             * {
             *  ConnectionString = WhatINeed,
             *  DBProvider = "MongoServer",
             *  Name = "Mongo",
             *  CommandText =
             *      @"insert into dbo.Log (
             *          Logged, Level, Message, Username, Url, Logger, Callsite, Exception, Stacktrace, remoteAddress
             *      ) values(
             *          @Logged, @Level, @Message, @Username, @Url, @Logger, @Callsite, @Exception, @Stacktrace, @remoteAddress
             *      );"
             * };
             *
             * // Adding all database parameters to pass through Mongo
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Logged", "${date}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Level", "${level}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Username", "${identity}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Url", "${I need this}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Logger", "${logger}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Callsite", "${callsite}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Exception", "${exception:format=toString}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@StackTrace", "${stacktrace}"));
             *
             * // Add the target to the config
             * config.AddTarget("database", dbTarget);
             *
             * var databaseRule = new LoggingRule("DatabaseRule", LogLevel.Trace, dbTarget);
             * config.LoggingRules.Add(databaseRule);
             */

            // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
            fileFlushWrapper.Condition = "level >= LogLevel.Info";

            // Adding the target to the config
            config.AddTarget("file", fileFlushWrapper);

            // Creating the Log Level rules for each target and adding them to the config
            var fileRule = new LoggingRule("*", fileTarget);

            fileRule.EnableLoggingForLevel(exceptionLevel);
            fileRule.EnableLoggingForLevels(minLevel, maxLevel);
            config.LoggingRules.Add(fileRule);

            /*
             * var consoleRule = new LoggingRule("*", consoleTarget);
             * consoleRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Info);
             * consoleRule.EnableLoggingForLevel(LogLevel.Error);
             * config.LoggingRules.Add(consoleRule);
             */

            // Assigning the configuration to the logger
            LogManager.Configuration = config;
        }
コード例 #54
0
        public static void  ConfigureLogging(string connectionString)
        {
            LogManager.ThrowExceptions = true;
            // Step 1. Create configuration object
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            var databaseTarget = new DatabaseTarget
            {
                CommandType      = CommandType.Text,
                ConnectionString = connectionString,
                DBProvider       = "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
                Name             = "database"
            };

            var messageParam = new DatabaseParameterInfo {
                Name = "@Message", Layout = "${message}"
            };
            var callsiteParam = new DatabaseParameterInfo {
                Name = "@Callsite", Layout = "${callsite}"
            };
            var levelParam = new DatabaseParameterInfo {
                Name = "@Level", Layout = "${level}"
            };
            var dateParam = new DatabaseParameterInfo {
                Name = "@Date", Layout = "${date}"
            };
            var loggerParam = new DatabaseParameterInfo {
                Name = "@Logger", Layout = "${logger}"
            };
            var exceptionParam = new DatabaseParameterInfo {
                Name = "@Exception", Layout = "${exception:tostring}"
            };

            databaseTarget.Parameters.Add(messageParam);
            databaseTarget.Parameters.Add(callsiteParam);
            databaseTarget.Parameters.Add(levelParam);
            databaseTarget.Parameters.Add(dateParam);
            databaseTarget.Parameters.Add(loggerParam);
            databaseTarget.Parameters.Add(exceptionParam);

            databaseTarget.CommandText = "INSERT INTO Logs (Date,Level,Logger, Message, Callsite, Exception) VALUES(@Date,@Level,@Logger, @Message, @Callsite, @Exception);";
            config.AddTarget("database", databaseTarget);

            // Step 4. Define rules
            var rule1 = new LoggingRule("*", LogLevel.Info, databaseTarget);

            config.LoggingRules.Add(rule1);


            var fileTarget = new FileTarget
            {
                Name       = "file",
                FileName   = "logs/${shortdate}.log",
                Layout     = "${date} ${logger} ${level}: ${message} ${exception:tostring}",
                CreateDirs = true
            };

            config.AddTarget(fileTarget);
            var rule2 = new LoggingRule("*", LogLevel.Info, fileTarget);

            config.LoggingRules.Add(rule2);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;
        }
コード例 #55
0
ファイル: NLogLogger.cs プロジェクト: JeetKunDoug/EventStore
 public NLogLogger(Type typeToLog, LoggingConfiguration configuration)
 {
     this.log = new LogFactory(configuration).GetLogger(typeToLog.FullName);
 }
コード例 #56
0
ファイル: Covenant.cs プロジェクト: xephora/Covenant
        static void Main(string[] args)
        {
            CommandLineApplication app = new CommandLineApplication();

            app.HelpOption("-? | -h | --help");
            var UserNameOption = app.Option(
                "-u | --username <USERNAME>",
                "The UserName to login to the Covenant API. (env: COVENANT_USERNAME)",
                CommandOptionType.SingleValue
                );
            var PasswordOption = app.Option(
                "-p | --password <PASSWORD>",
                "The Password to login to the Covenant API. (env: COVENANT_PASSWORD)",
                CommandOptionType.SingleValue
                );
            var ComputerNameOption = app.Option(
                "-c | --computername <COMPUTERNAME>",
                "The ComputerName (IPAddress or Hostname) to bind the Covenant API to. (env: COVENANT_COMPUTER_NAME)",
                CommandOptionType.SingleValue
                );

            app.OnExecute(() =>
            {
                if (!File.Exists(Path.Combine(Common.CovenantSharpSploitDirectory, "SharpSploit.sln")) ||
                    !File.Exists(Path.Combine(Common.CovenantRubeusDirectory, "Rubeus.sln")))
                {
                    Console.Error.WriteLine("Error: git submodules have not been initialized");
                    Console.Error.WriteLine("Covenant's submodules can be cloned with: git clone --recurse-submodules https://github.com/cobbr/Covenant");
                    Console.Error.WriteLine("Or initialized after cloning with: git submodule update --init --recursive");
                    return(-1);
                }

                string username = UserNameOption.HasValue() ? UserNameOption.Value() : Environment.GetEnvironmentVariable("COVENANT_USERNAME");
                string password = PasswordOption.HasValue() ? PasswordOption.Value() : Environment.GetEnvironmentVariable("COVENANT_PASSWORD");
                if (!string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password))
                {
                    Console.Write("Password: "******"COVENANT_COMPUTER_NAME");;
                if (string.IsNullOrEmpty(CovenantBindUrl))
                {
                    CovenantBindUrl = "0.0.0.0";
                }

                IPAddress address = null;
                try
                {
                    address = IPAddress.Parse(CovenantBindUrl);
                }
                catch (FormatException)
                {
                    address = Dns.GetHostAddresses(CovenantBindUrl).FirstOrDefault();
                }
                IPEndPoint CovenantEndpoint = new IPEndPoint(address, Common.CovenantHTTPSPort);
                string CovenantUri          = (CovenantBindUrl == "0.0.0.0" ? "https://127.0.0.1:" + Common.CovenantHTTPSPort : "https://" + CovenantEndpoint);
                var host = BuildWebHost(CovenantEndpoint, CovenantUri);
                using (var scope = host.Services.CreateScope())
                {
                    var services             = scope.ServiceProvider;
                    var context              = services.GetRequiredService <CovenantContext>();
                    var userManager          = services.GetRequiredService <UserManager <CovenantUser> >();
                    var signInManager        = services.GetRequiredService <SignInManager <CovenantUser> >();
                    var roleManager          = services.GetRequiredService <RoleManager <IdentityRole> >();
                    var configuration        = services.GetRequiredService <IConfiguration>();
                    var listenerTokenSources = services.GetRequiredService <ConcurrentDictionary <int, CancellationTokenSource> >();
                    context.Database.EnsureCreated();
                    DbInitializer.Initialize(context, roleManager, listenerTokenSources).Wait();
                    if (!context.Users.Any() && !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                    {
                        CovenantUser user = new CovenantUser {
                            UserName = username
                        };
                        Task <IdentityResult> task = userManager.CreateAsync(user, password);
                        task.Wait();
                        IdentityResult userResult = task.Result;
                        if (userResult.Succeeded)
                        {
                            userManager.AddToRoleAsync(user, "User").Wait();
                            userManager.AddToRoleAsync(user, "Administrator").Wait();
                        }
                        else
                        {
                            Console.Error.WriteLine($"Error creating user: {user.UserName}");
                            return(-1);
                        }
                    }
                }

                LoggingConfiguration loggingConfig = new LoggingConfiguration();
                var consoleTarget = new ColoredConsoleTarget();
                var fileTarget    = new FileTarget();
                loggingConfig.AddTarget("console", consoleTarget);
                loggingConfig.AddTarget("file", fileTarget);
                consoleTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}";
                fileTarget.Layout    = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}";
                fileTarget.FileName  = Common.CovenantLogDirectory + "covenant.log";
                loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "console");
                loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "file");

                var logger = NLogBuilder.ConfigureNLog(loggingConfig).GetCurrentClassLogger();
                try
                {
                    logger.Debug("Starting Covenant API");
                    if (!IsElevated())
                    {
                        Console.Error.WriteLine("WARNING: Running Covenant non-elevated. You may not have permission to start Listeners on low-numbered ports. Consider running Covenant elevated.");
                    }
                    host.Run();
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "Covenant stopped due to exception");
                    throw;
                }
                finally
                {
                    NLog.LogManager.Shutdown();
                }
                return(0);
            });
            app.Execute(args);
        }
コード例 #57
0
        public async Task TestCurrentManagedThreadIdMatchesCaller()
        {
            var loggingConfiguration = new LoggingConfiguration();
            var target = new TestFileTarget(new CurrentManagedThreadIdLayout());
            loggingConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal, target);
            LogManagerFactory.DefaultConfiguration = loggingConfiguration;
            var log = (ILoggerAsync)LogManagerFactory.DefaultLogManager.GetLogger<FileStreamingTargetTests>();

            for (int i = 0; i < 100; i++)
            {
                var expectedThreadId = Environment.CurrentManagedThreadId;
                await log.TraceAsync("What thread am I?");
                var output = target.Stream.ToArray();
                target.Stream.Position = 0;
                var loggedThreadId = int.Parse(Encoding.UTF8.GetString(output, 0, output.Length));
                Assert.Equal(expectedThreadId, loggedThreadId);
            }
        }
コード例 #58
0
        public void ReconfigureDoesNotDisposeListenersStillUsedInSpecialSources()
        {
            var traceListener = new MockDisposableTraceListener();

            var config = new LoggingConfiguration();
            config.AddLogSource("General", traceListener);

            var logWriter = new LogWriter(config);
            logWriter.Configure((cfg) =>
            {
                cfg.LogSources.Clear();

                cfg.AddLogSource("New", new DefaultTraceListener());
                cfg.SpecialSources.AllEvents.Listeners.Add(traceListener);
            });

            Assert.AreEqual(0, traceListener.DisposedCalls);
        }
コード例 #59
0
        public async Task <bool> DownloadFeedSchema(string DownloadPath, DownloadFeedSchemaRequest reqModel, ConnectSetting connectSetting = null, LoggingConfiguration logSetting = null)
        {
            var request = CreateRequest <DownloadFeedSchemaRequest>(reqModel);

            request.URI = "sellermgmt/seller/feedschema";

            var response = await client.PutAsync(request, connectSetting);

            byte[] content = await response.RawResponse.Content.ReadAsByteArrayAsync();

            System.IO.File.WriteAllBytes(DownloadPath, content);

            return(true);
        }
コード例 #60
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="NLogFactory" /> class.
 /// </summary>
 /// <param name="loggingConfiguration"> The NLog Configuration </param>
 public NLogFactory(LoggingConfiguration loggingConfiguration)
 {
     LogManager.Configuration = loggingConfiguration;
 }