Esempio n. 1
0
        public void InitializeLogger()
        {
            var config = new NLog.Config.LoggingConfiguration();

            LogManager.Configuration = config;
            const string layout =
                @"${date:format=yyyy-MM-dd HH\:mm\:ss,fff} ${level:upperCase=True} ${logger} ${message}${newline}${onexception:Process\: ${processname}${newline}Process time\: ${processtime}${newline}Process ID\: ${processid}${newline}Thread ID\: ${threadid}${newline}Details\:${newline}${exception:format=ToString}}";
            var boxTarget = new RichTextBoxTarget
            {
                Layout      = layout,
                ControlName = "syntaxRichTextBox1",
                FormName    = "MainDlg",
                UseDefaultRowColoringRules = false
            };

            boxTarget.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "Orange", "White",
                                                                          FontStyle.Regular));
            boxTarget.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "Red", "White",
                                                                          FontStyle.Regular));
            boxTarget.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "DarkViolet", "White",
                                                                          FontStyle.Regular));

            var traceTarget = new TraceTarget {
                Layout = layout
            };

            config.AddTarget("box", boxTarget);
            config.AddTarget("trace", traceTarget);
            var r1 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Warn, boxTarget);
            var r2 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, traceTarget);

            config.LoggingRules.Add(r1);
            config.LoggingRules.Add(r2);
            LogManager.Configuration = config;
        }
Esempio n. 2
0
        private static void SetupLogging()
        {
            LoggingConfiguration logConfiguration = new LoggingConfiguration();

            LogLevel level = LogLevel.Trace;

            TraceTarget ttarget = new TraceTarget();

            logConfiguration.AddTarget("tt", ttarget);
            LoggingRule ttRule = new LoggingRule("*", level, ttarget);

            logConfiguration.LoggingRules.Add(ttRule);

            FileTarget fileTarget = new FileTarget();

            logConfiguration.AddTarget("file", fileTarget);
            fileTarget.FileName         = "debug-test.log";
            fileTarget.Layout           = "${longdate}|[${threadid:padding=4}]|${level:uppercase=true:padding=5}|${message}${exception:format=ToString}";
            fileTarget.ArchiveEvery     = FileArchivePeriod.Day;
            fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date;
            fileTarget.MaxArchiveFiles  = 7;

            LoggingRule rule2 = new LoggingRule("*", level, fileTarget);

            logConfiguration.LoggingRules.Add(rule2);

            LogManager.Configuration = logConfiguration;
            LogManager.ReconfigExistingLoggers();
        }
Esempio n. 3
0
        public void Log_Trace()
        {
            string traceId       = "105445aa7843bc8bf206b12000100f00";
            string fullTraceName = TraceTarget.ForProject(ProjectId).GetFullTraceName(traceId);

            Predicate <IEnumerable <LogEntry> > matcher = logEntries =>
            {
                LogEntry entry = logEntries.Single();
                return(entry.LogName == new LogName(ProjectId, BaseLogName).ToString() &&
                       entry.Trace == fullTraceName);
            };

            var tracerContext     = TraceHeaderContext.Create(traceId, 81237123, null);
            HeaderDictionary dict = new HeaderDictionary();

            dict[TraceHeaderContext.TraceHeader] = tracerContext.ToString();

            var mockServiceProvider = new Mock <IServiceProvider>();
            var mockAccessor        = new Mock <IHttpContextAccessor>();
            var mockContext         = new Mock <HttpContext>();
            var mockRequest         = new Mock <HttpRequest>();

            mockServiceProvider.Setup(sp => sp.GetService(typeof(IHttpContextAccessor))).Returns(mockAccessor.Object);
            mockAccessor.Setup(a => a.HttpContext).Returns(mockContext.Object);
            mockContext.Setup(c => c.Request).Returns(mockRequest.Object);
            mockRequest.Setup(r => r.Headers).Returns(dict);

            var mockConsumer = new Mock <IConsumer <LogEntry> >();

            mockConsumer.Setup(c => c.Receive(Match.Create(matcher)));
            var logger = GetLogger(mockConsumer.Object, LogLevel.Information, serviceProvider: mockServiceProvider.Object, logName: BaseLogName);

            logger.Log(LogLevel.Error, 0, LogMessage, s_exception, Formatter);
            mockConsumer.VerifyAll();
        }
Esempio n. 4
0
        private void ConfigureLogging()
        {
            var config = new LoggingConfiguration();

            var target = new TraceTarget();

            target.Layout = @"${message}";
            config.AddTarget("debugger", target);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target));

            string path       = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "GameBot_ExtractionComparison.csv");
            var    fileTarget = new FileTarget();

            fileTarget.Layout   = @"${message}";
            fileTarget.FileName = path;
            config.AddTarget("file", fileTarget);
            config.LoggingRules.Add(new LoggingRule("ExtractionComparison", LogLevel.Debug, fileTarget));

            path                = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "GameBot_ExtractionDetails.csv");
            fileTarget          = new FileTarget();
            fileTarget.Layout   = @"${message}";
            fileTarget.FileName = path;
            config.AddTarget("file", fileTarget);
            config.LoggingRules.Add(new LoggingRule("ExtractionDetails", LogLevel.Debug, fileTarget));

            path                = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "GameBot_Tests_Fails.txt");
            fileTarget          = new FileTarget();
            fileTarget.Layout   = @"${message}";
            fileTarget.FileName = path;
            config.AddTarget("file", fileTarget);
            config.LoggingRules.Add(new LoggingRule("Fails", LogLevel.Debug, fileTarget));

            LogManager.Configuration = config;
        }
Esempio n. 5
0
        private void initLog()
        {
            var path = HostingEnvironment.MapPath("~/App_Data");

            var config = new LoggingConfiguration();

            var fileTarget = new FileTarget()
            {
                FileName         = Path.Combine(path, "activity.log"),
                ArchiveFileName  = Path.Combine(path, "activity.{#####}.log"),
                ArchiveAboveSize = 1024 * 1024,
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                ConcurrentWrites = false,
                Layout           = "${longdate} | ${level} | ${logger} | ${message} ${exception:format=tostring}",
                AutoFlush        = true,
                MaxArchiveFiles  = 50
            };

            config.AddTarget("file", fileTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));

            var traceTarget = new TraceTarget()
            {
                Layout = "${level} | ${logger} | ${message} ${exception:format=tostring}"
            };

            config.AddTarget("trace", traceTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, traceTarget));

            LogManager.Configuration = config;
        }
Esempio n. 6
0
        private void InitLog()
        {
            var config   = new LoggingConfiguration();
            var basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Q3");
            //var basePath = AppDomain.CurrentDomain.BaseDirectory;

            var fileTarget = new FileTarget()
            {
                FileName         = Path.Combine(basePath, "activity.log"),
                ArchiveFileName  = Path.Combine(basePath, "activity.{#####}.log"),
                ArchiveAboveSize = 1024 * 1024,
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                ConcurrentWrites = false,
                Layout           = "${longdate} | ${level} | ${logger} | ${message} ${exception:format=tostring}",
                AutoFlush        = true,
                MaxArchiveFiles  = 50
            };

            config.AddTarget("file", fileTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));

            var traceTarget = new TraceTarget()
            {
                Layout = "${level} | ${logger} | ${message} ${exception:format=tostring}"
            };

            config.AddTarget("trace", traceTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, traceTarget));

            LogManager.Configuration = config;

            logger.Info("startup " + Assembly.GetExecutingAssembly().GetName().ToString());
        }
        public void Log_Trace()
        {
            string traceId       = "external_trace_id";
            string spanId        = "external_span_id";
            string fullTraceName = TraceTarget.ForProject(ProjectId).GetFullTraceName(traceId);

            Predicate <IEnumerable <LogEntry> > matcher = logEntries =>
            {
                LogEntry entry = logEntries.Single();
                return(entry.LogName == new LogName(ProjectId, BaseLogName).ToString() &&
                       entry.Trace == fullTraceName &&
                       entry.SpanId == spanId);
            };

            var mockServiceProvider       = new Mock <IServiceProvider>();
            var mockExternalTraceProvider = new Mock <IExternalTraceProvider>();

            mockServiceProvider.Setup(sp => sp.GetService(typeof(IExternalTraceProvider))).Returns(mockExternalTraceProvider.Object);
            mockExternalTraceProvider.Setup(
                sp => sp.GetCurrentTraceContext(It.IsAny <IServiceProvider>()))
            .Returns(new TraceContextForLogEntry(traceId, spanId));

            var mockConsumer = new Mock <IConsumer <LogEntry> >();

            mockConsumer.Setup(c => c.Receive(Match.Create(matcher)));
            var logger = GetLogger(mockConsumer.Object, LogLevel.Information, serviceProvider: mockServiceProvider.Object, logName: BaseLogName);

            logger.Log(LogLevel.Error, 0, LogMessage, s_exception, Formatter);
            mockConsumer.VerifyAll();
        }
        public void GetFullLogName_Project()
        {
            string      traceId   = "trace-id";
            TraceTarget target    = TraceTarget.ForProject(_pid);
            string      traceName = target.GetFullTraceName(traceId);

            Assert.Contains(traceId, traceName);
            Assert.Contains(_pid, traceName);
        }
        static void ConfigureLogging()
        {
            var config      = new LoggingConfiguration();
            var traceTarget = new TraceTarget();

            config.AddTarget("Diagnostic", traceTarget);
            var traceRule = new LoggingRule("*", LogLevel.Debug, traceTarget);

            config.LoggingRules.Add(traceRule);
            LogManager.Configuration = config;
            log = LogManager.GetCurrentClassLogger();
        }
Esempio n. 10
0
        public LogConfigBuilder AddDebugAppender(LogLevel logLevel = null, string layout = DefaultConsoleLayout)
        {
            var debugTarget = new TraceTarget
            {
                Layout = layout
            };

            _loggingConfiguration.AddTarget("debug", debugTarget);
            _loggingConfiguration.LoggingRules.Add(new LoggingRule("*", logLevel ?? LogLevel.Debug, debugTarget));

            return(this);
        }
Esempio n. 11
0
        /// <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 TraceTarget();
                trace.Name = "emulator_trace";
                config.AddTarget("emulator_trace", trace);

                foreach (var rule in config.LoggingRules)
                {
                    rule.Targets.Add(trace);
                }
            }
        }
Esempio n. 12
0
 internal GoogleLogger(IConsumer <LogEntry> consumer, LogTarget logTarget, LoggerOptions loggerOptions,
                       string logName, IClock clock = null, IServiceProvider serviceProvider = null)
 {
     _logTarget   = GaxPreconditions.CheckNotNull(logTarget, nameof(logTarget));
     _traceTarget = logTarget.Kind == LogTargetKind.Project ?
                    TraceTarget.ForProject(logTarget.ProjectId) : null;
     _consumer        = GaxPreconditions.CheckNotNull(consumer, nameof(consumer));
     _loggerOptions   = GaxPreconditions.CheckNotNull(loggerOptions, nameof(loggerOptions));
     _logName         = GaxPreconditions.CheckNotNullOrEmpty(logName, nameof(logName));
     _fullLogName     = logTarget.GetFullLogName(_loggerOptions.LogName);
     _serviceProvider = serviceProvider;
     _clock           = clock ?? SystemClock.Instance;
 }
Esempio n. 13
0
 internal GoogleLogger(IConsumer <LogEntry> consumer, LogTarget logTarget, LoggerOptions loggerOptions,
                       string logName, IClock clock = null, IHttpContextAccessor accessor = null)
 {
     GaxPreconditions.CheckNotNull(logTarget, nameof(logTarget));
     GaxPreconditions.CheckNotNullOrEmpty(logName, nameof(logName));
     _traceTarget = logTarget.Kind == LogTargetKind.Project ?
                    TraceTarget.ForProject(logTarget.ProjectId) : null;
     _consumer      = GaxPreconditions.CheckNotNull(consumer, nameof(consumer));
     _loggerOptions = GaxPreconditions.CheckNotNull(loggerOptions, nameof(loggerOptions));;
     _logName       = logTarget.GetFullLogName(logName);
     _accessor      = accessor;
     _clock         = clock ?? SystemClock.Instance;
 }
Esempio n. 14
0
        public void OnAssemblyStart()
        {
            var configuration        = new LoggingConfiguration();
            var unitTestRunnerTarget = new TraceTarget();

            configuration.AddTarget("Unit test runner", unitTestRunnerTarget);
            unitTestRunnerTarget.Layout = "${time}|${pad:padding=-5:inner=${uppercase:${level}}}|${message}";
            var logEverything = new LoggingRule("*", LogLevel.Debug, unitTestRunnerTarget);

            configuration.LoggingRules.Add(logEverything);
            LogManager.Configuration = configuration;
            log = LogManager.GetCurrentClassLogger();
            log.Info("Logging initialized");
        }
Esempio n. 15
0
    static void Main(string[] args)
    {
        Trace.Listeners.Add(new ConsoleTraceListener());

        TraceTarget target = new TraceTarget();

        target.Layout = "${message}";

        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);

        Logger logger = LogManager.GetLogger("Example");

        logger.Debug("log message");
    }
Esempio n. 16
0
        public AutomationLogging()
        {
            string resultFolder = @"C:/WDTF/TestResult";
            string asm          = Assembly.GetCallingAssembly().FullName;
            string logFormat    = string.Format("{0:yyyy-MM-dd-hh-mm-ss}", DateTime.Now);

            newLocationInResultFolder = resultFolder + "/" + currentGuid + "_" + logFormat;
            DirectoryInfo directoryInfo = new DirectoryInfo(newLocationInResultFolder);

            if (!directoryInfo.Exists)
            {
                System.IO.Directory.CreateDirectory(newLocationInResultFolder);
            }
            var config = new LoggingConfiguration();


            //===========================================================================================//
            var consoleTarget = new ColoredConsoleTarget();

            consoleTarget.Layout = "${time} | ${level}  | ${stacktrace::topFrames=2}|${message} ";
            config.AddTarget("console", consoleTarget);
            LoggingRule consoleInfo = new LoggingRule("*", LogLevel.Debug, consoleTarget);

            config.LoggingRules.Add(consoleInfo);
            //===========================================================================================//
            var fileTarget = new FileTarget();

            fileTarget.Layout = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ";

            fileTarget.FileName = newLocationInResultFolder + "/" + className + "_" + logFormat + DateTime.Now.Second + ".log";
            config.AddTarget("file", fileTarget);
            var fileInfo = new LoggingRule("*", LogLevel.Debug, fileTarget);

            config.LoggingRules.Add(fileInfo);
            //===========================================================================================//
            TraceTarget traceTarget = new TraceTarget();

            traceTarget.Layout = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ";

            //===========================================================================================//

            //===========================================================================================//
            DatabaseTarget dbTarget = new DatabaseTarget();

            //===========================================================================================//

            // Step 4. Define rules
            LogManager.Configuration = config;
            Console.WriteLine(logger.IsDebugEnabled);
        }
Esempio n. 17
0
        public void OnAssemblyStart()
        {
            var configuration        = new LoggingConfiguration();
            var unitTestRunnerTarget = new TraceTarget();

            configuration.AddTarget("Unit test runner", unitTestRunnerTarget);
            unitTestRunnerTarget.Layout =
                "${time}|${pad:padding=-5:inner=${uppercase:${level}}}|${pad:padding=-16:inner=${callsite:className=true:fileName=false:includeSourcePath=false:methodName=false:includeNamespace=false}}|${message}";
            unitTestRunnerTarget.RawWrite = true;
            var logEverything = new LoggingRule("*", LogLevel.Trace, unitTestRunnerTarget);

            configuration.LoggingRules.Add(logEverything);
            LogManager.Configuration = configuration;
            log = LogManager.GetCurrentClassLogger();
            log.Info("Logging initialized");
        }
Esempio n. 18
0
        public static void TryInitNLog()
        {
            if (LogManager.Configuration == null)
            {
                LoggingConfiguration LogConfig = new LoggingConfiguration();

                //status icon warning/errors
                MethodCallTarget StatusIconTarget = new MethodCallTarget();
                StatusIconTarget.ClassName  = typeof(LzsLogging).AssemblyQualifiedName;
                StatusIconTarget.MethodName = "LogWarningOrError";
                StatusIconTarget.Parameters.Add(new MethodCallParameter("${level}"));
                LoggingRule StatusIconRule = new LoggingRule("*", LogLevel.Warn, StatusIconTarget);
                LogConfig.AddTarget("StatusIcon", StatusIconTarget);
                LogConfig.LoggingRules.Add(StatusIconRule);

                //File log
                FileTarget LogFileTarget = new FileTarget();
                LogFileTarget.FileName                = @"${basedir}/Components/Lazysplits/logs/log.txt";
                LogFileTarget.ArchiveNumbering        = NLog.Targets.ArchiveNumberingMode.Date;
                LogFileTarget.ArchiveDateFormat       = "yyyyMMddHHmmss";
                LogFileTarget.MaxArchiveFiles         = 20;
                LogFileTarget.ArchiveOldFileOnStartup = true;
                #if DEBUG
                LogFileTarget.Layout = @"NLog|${date:format=HH\:mm\:ss.ff}|${pad:padding=5:inner=${level}}|${logger}|${message}";
                LoggingRule FileRule = new LoggingRule("*", LogLevel.Trace, LogFileTarget);
                #else
                LogFileTarget.Layout = @"NLog|${date:format=HH\:mm\:ss.ff}|${logger}|${message}";
                LoggingRule FileRule = new LoggingRule("*", LogLevel.Info, LogFileTarget);
                #endif

                LogConfig.AddTarget("File", LogFileTarget);
                LogConfig.LoggingRules.Add(FileRule);

                //console log
                #if DEBUG
                TraceTarget LogTraceTarget = new TraceTarget();
                LogTraceTarget.Layout = @"NLog|${date:format=HH\:mm\:ss.ff}|${pad:padding=5:inner=${level}}|${logger}|${message}";
                LoggingRule TraceRule = new LoggingRule("*", LogLevel.Trace, LogTraceTarget);
                LogConfig.AddTarget("File", LogTraceTarget);
                LogConfig.LoggingRules.Add(TraceRule);
                #endif

                LogManager.Configuration = LogConfig;
            }
        }
Esempio n. 19
0
        static LoggingConfiguration CreateLoggingConfiguration()
        {
            var log    = new LoggingConfiguration();
            var layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}";

            var targetConsole = new ColoredConsoleTarget {
                Layout = layout
            };

            log.AddTarget("console", targetConsole);
            log.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, targetConsole));

            var targetLogfile = new FileTarget
            {
                FileName         = "${basedir}/" + ServiceName + "-${machinename}-{#####}.log",
                Layout           = layout,
                ArchiveNumbering = ArchiveNumberingMode.DateAndSequence,
                ArchiveEvery     = FileArchivePeriod.Minute
            };

            log.AddTarget("logfile", targetLogfile);
            log.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, targetLogfile));

            var targetTrace = new TraceTarget();

            log.AddTarget("trace", targetTrace);
            log.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, targetTrace));

            //var azureTarget = new AzureAppendBlobTarget
            //{
            //    ConnectionString = AzureConnectionString,
            //    Layout = layout,
            //    Name = "azure",
            //    BlobName = ServiceName + "-${machinename}.log",
            //    Container = $"logs-{Environment.MachineName.ToLower()}"
            //};
            //log.AddTarget("azure", azureTarget);
            //log.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, azureTarget));

            return(log);
        }
Esempio n. 20
0
        static void ConfigureLogging(string logLevelString)
        {
            var logLevel = GetLogLevel(logLevelString);
            var config   = new LoggingConfiguration();

#if DEBUG
            var traceTarget = new TraceTarget
            {
                Layout = @"${message}"
            };
            config.AddTarget("debugger", traceTarget);
            config.LoggingRules.Add(new LoggingRule("*", logLevel, traceTarget));
#endif
            var fileTarget = new FileTarget
            {
                Layout   = @"${longdate} | ${level:uppercase=true} | ${pad:padding=-58:inner=${logger}} | ${message}",
                FileName = GetLogPath()
            };
            config.AddTarget("file", fileTarget);
            config.LoggingRules.Add(new LoggingRule("*", logLevel, fileTarget));

            LogManager.Configuration = config;
        }
Esempio n. 21
0
 public TraceOn(TraceTarget traceTarget)
 {
     Target = traceTarget;
 }
Esempio n. 22
0
		public void UnregisterTraceTarget() 
		{
			traceTarget = null;
		}
Esempio n. 23
0
		public void RegisterTraceTarget(TraceTarget newTraceTarget) 
		{
			traceTarget = newTraceTarget;
		}
Esempio n. 24
0
        /// <summary>
        /// Sets the config.
        /// </summary>
        /// <param name="connectionstring">The connectionstring.</param>
        /// <param name="console">The console.</param>
        /// <param name="file">The file.</param>
        /// <param name="database">The database.</param>
        /// <returns></returns>
        public static LoggingConfiguration SetConfig(string connectionstring, bool?console = null, bool?file = null, bool?database = null)
        {
            // Step 1. Create configuration object
            var config = new LoggingConfiguration();

            #region Console

            if (console.HasValue ? console.Value :  true)
            {
                // Step 2. Create targets and add them to the configuration
                var consoleTarget = new TraceTarget();
                config.AddTarget("console", consoleTarget);

                // Step 3. Set target properties
                consoleTarget.Layout = string.Format("${{date:format=HH\\:mm\\:ss.fff}} ${{level}} ${{event-context:item={0}}} ${{event-context:item={1}}} ${{message}} ${{event-context:item={2}}} ${{event-context:item={3}}} ${{event-context:item={4}}} ${{event-context:item={5}}} ${{event-context:item={6}}} ${{event-context:item={7}}} ${{event-context:item={8}}}", NLogExceptionType, NLogExceptionId, NLogApplication, NLogAppVersion, NLogVerb, NLogRequestUrl, NLogJSonSession, NLogJsonRequest, NLogCorrId);

                // Step 4. Define rules

                LogLevel level = LogLevel.Trace;

                var rule1 = new LoggingRule("*", level, consoleTarget);
                config.LoggingRules.Add(rule1);
            }

            #endregion

            #region File

            if (file.HasValue ? file.Value :  !console.GetValueOrDefault())
            {
                var fileTarget       = new FileTarget();
                var asyncwrapperFile = new NLog.Targets.Wrappers.AsyncTargetWrapper(fileTarget);
                //            fileTarget.FileName = string.Format("${{basedir}}\\{{$event-context:item={0}}}\\${{shortdate}}_${{level}}.log", NLogApplication);
                fileTarget.FileName = string.Format("{0}/${{shortdate}}_${{level}}.log", "${basedir}/log");
                fileTarget.Layout   = string.Format("\n${{date:format=HH\\:mm\\:ss}} ${{level}} ${{event-context:item={0}}} ${{event-context:item={1}}} ${{event-context:item={2}}}\n${{message}}\n${{event-context:item={3}}} ${{event-context:item={4}}} ${{event-context:item={5}}} ${{event-context:item={6}}} ${{event-context:item={7}}} ${{event-context:item={8}}}", NLogExceptionType, NLogExceptionId, NLogApplication, NLogAppVersion, NLogVerb, NLogRequestUrl, NLogJsonRequest, NLogJSonSession, NLogCorrId);
                config.AddTarget("file", asyncwrapperFile);

                LogLevel level = LogLevel.Error;
                var      rule2 = new LoggingRule("*", level, asyncwrapperFile);
                // filter na vstupne parametre
                rule2.Filters.Add(new ConditionBasedFilter {
                    Condition = "equals('${logger}','StringMapTypeDeserializer')", Action = FilterResult.Ignore
                });
                config.LoggingRules.Add(rule2);
            }

            #endregion

            #region Database

            if (database.HasValue ? database.Value : true)
            {
                var databaseTarget = new DatabaseTarget();
                //  NLog.Targets.Wrappers.AsyncTargetWrapper asyncwrapperDb = new NLog.Targets.Wrappers.AsyncTargetWrapper(databaseTarget);
                databaseTarget.ConnectionString = connectionstring;
                databaseTarget.CommandText      = "set context_info 0x50006F00730074004400650070006C006F007900;INSERT INTO [reg].[D_Log]([Application],[Version],[machine],[Log_Level],[Logger],[Verb],[RequestUrl],[JsonSession],[JsonRequest],[Message],[LastSoapRequestMessage],[LastSoapResponseMessage],[ErrorType],[ErrorIdentifier],[CorrId]) VALUES (@Application,@Version,@machine,@Log_Level,@Logger,@Verb,@RequestUrl,@JsonSession,@JsonRequest,@Message,@LastSoapRequestMessage,@LastSoapResponseMessage,@ErrorType,@ErrorIdentifier,@CorrId)";
                databaseTarget.KeepConnection   = false;
                databaseTarget.Name             = "DLog";

                var param = new DatabaseParameterInfo();
                param.Name   = "@Application";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogApplication);
                databaseTarget.Parameters.Add(param);

                /*param = new DatabaseParameterInfo();
                 * param.Name = "@Time_Stamp";
                 * param.Layout = "${date}";
                 * databaseTarget.Parameters.Add(param);
                 */
                param        = new DatabaseParameterInfo();
                param.Name   = "@Log_Level";
                param.Layout = "${level}";
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@Logger";
                param.Layout = "${logger}";
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@Verb";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogVerb);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@RequestUrl";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogRequestUrl);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@JsonSession";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogJSonSession);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@JsonRequest";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogJsonRequest);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@Version";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogAppVersion);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@LastSoapRequestMessage";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogLastSoapRequestMessage);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@LastSoapResponseMessage";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogLastSoapResponseMessage);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@CorrId";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogCorrId);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@machine";
                param.Layout = "${machinename}";
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@Message";
                param.Layout = "${message}";
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@ErrorType";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogExceptionType);
                databaseTarget.Parameters.Add(param);

                param        = new DatabaseParameterInfo();
                param.Name   = "@ErrorIdentifier";
                param.Layout = string.Format("${{event-context:item={0}}}", NLogExceptionId);
                databaseTarget.Parameters.Add(param);

                //config.AddTarget("database", asyncwrapperDb);
                config.AddTarget("database", databaseTarget);

                LogLevel level  = LogLevel.Warn;
                var      ruleDb = new LoggingRule("*", level, databaseTarget);
                // filter na vstupne parametre
                ruleDb.Filters.Add(new ConditionBasedFilter {
                    Condition = "equals('${logger}','StringMapTypeDeserializer')", Action = FilterResult.Ignore
                });

                // ruleDb.Filters.Add(new NLog.Filters.Filter());
                //var ruleDb = new LoggingRule("*", LogLevel.Error, asyncwrapperDb);
                config.LoggingRules.Add(ruleDb);
            }

            #endregion

            #region GrayLog

            /*
             * var greyLogHost = WebConfigurationManager.AppSettings["GreyLogHost"];
             * if (!string.IsNullOrEmpty(greyLogHost))
             * {
             *  var greyLogHostParsed = greyLogHost.Split(':');
             *  if (greyLogHostParsed.Length >= 3 && int.TryParse(greyLogHostParsed[2], out int remotePort))
             *  {
             *      var assembly = System.Reflection.Assembly.Load("EasyGelf.NLog");
             *      ConfigurationItemFactory.Default.RegisterItemsFromAssembly(assembly);
             *
             *      EasyGelf.NLog.GelfTargetBase gelfTarget = null;
             *      var remoteAddress = greyLogHostParsed[0];
             *      var transportType = greyLogHostParsed[1];
             *      LogLevel level = (greyLogHostParsed.Length > 3 ? string.IsNullOrEmpty(greyLogHostParsed[3]) : true) ? LogLevel.Trace : LogLevel.FromString(greyLogHostParsed[3]);
             *
             *      if (transportType == "tcp")
             *      {
             *          gelfTarget = new EasyGelf.NLog.GelfTcpTarget()
             *          {
             *              Facility = WebEasNLogLogger.Application,
             *              RemoteAddress = remoteAddress,
             *              RemotePort = remotePort
             *          };
             *      }
             *
             *      if (transportType == "udp")
             *      {
             *          gelfTarget = new EasyGelf.NLog.GelfUdpTarget()
             *          {
             *              Facility = WebEasNLogLogger.Application,
             *              RemoteAddress = remoteAddress,
             *              RemotePort = remotePort
             *          };
             *      }
             *
             *      if (gelfTarget != null)
             *      {
             *          config.AddTarget("gelfTarget", gelfTarget);
             *          gelfTarget.Layout = string.Format("${{date:format=HH\\:MM\\:ss}} ${{level}} ${{event-context:item={0}}} ${{event-context:item={1}}} ${{message}} ${{event-context:item={2}}} ${{event-context:item={3}}} ${{event-context:item={4}}} ${{event-context:item={5}}} ${{event-context:item={6}}} ${{event-context:item={7}}} ${{event-context:item={8}}}", NLogExceptionType, NLogExceptionId, NLogApplication, NLogAppVersion, NLogVerb, NLogRequestUrl, NLogJSonSession, NLogJsonRequest, NLogCorrId);
             *          //gelfTarget.Layout = "${message}";
             *          config.LoggingRules.Add(new LoggingRule("*", level, gelfTarget));
             *      }
             *  }
             * }
             */
            #endregion
            // Step 5. Activate the configuration
            LogManager.Configuration   = config;
            LogManager.ThrowExceptions = true;
            LogManager.ReconfigExistingLoggers();

            return(config);
        }
Esempio n. 25
0
 public void RegisterTraceTarget(TraceTarget newTraceTarget)
 {
     traceTarget = newTraceTarget;
 }
        public void Project()
        {
            TraceTarget target = TraceTarget.ForProject(_pid);

            Assert.Equal(_pid, target.ProjectId);
        }
Esempio n. 27
0
		public void RegisterTraceTarget(TraceTarget newTraceTarget) 
		{
            this.SetSamplerState(0, SamplerStatetraceTarget = newTraceTarget;
		}
Esempio n. 28
0
 public void UnregisterTraceTarget()
 {
     traceTarget = null;
 }
Esempio n. 29
0
        public AutomationLogging()
        {
            string resultFolder = @"C:/WDTF/TestResult";
            string asm          = Assembly.GetCallingAssembly().FullName;
            string logFormat    = string.Format("{0:yyyy-MM-dd-hh-mm-ss}", DateTime.Now);

            newLocationInResultFolder = resultFolder + "/" + currentGuid + "_" + logFormat;
            DirectoryInfo directoryInfo = new DirectoryInfo(newLocationInResultFolder);

            if (!directoryInfo.Exists)
            {
                System.IO.Directory.CreateDirectory(newLocationInResultFolder);
            }
            LoggingConfiguration config = new LoggingConfiguration();


            //===========================================================================================//
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget
            {
                Layout = "${time} | ${level}  | ${stacktrace::topFrames=2}|${message} "
            };

            config.AddTarget("console", consoleTarget);
            LoggingRule consoleInfo = new LoggingRule("*", NLog.LogLevel.Info, consoleTarget);

            config.LoggingRules.Add(consoleInfo);
            //===========================================================================================//
            FileTarget fileTarget = new FileTarget
            {
                Layout   = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ",
                FileName = newLocationInResultFolder + "/" + className + "_" + logFormat + DateTime.Now.Second + ".log"
            };

            config.AddTarget("file", fileTarget);
            LoggingRule fileInfo = new LoggingRule("*", NLog.LogLevel.Info, fileTarget);

            config.LoggingRules.Add(fileInfo);
            //===========================================================================================//
            TraceTarget traceTarget = new TraceTarget
            {
                Layout = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} "
            };

            //===========================================================================================//
            MailTarget mailTarget = new MailTarget
            {
                Name               = "gmail",
                SmtpServer         = "smtp.gmail.com",
                SmtpPort           = 465,
                SmtpAuthentication = SmtpAuthenticationMode.Basic,
                SmtpUserName       = "******",
                SmtpPassword       = "******",
                EnableSsl          = true,
                From               = "*****@*****.**",
                To = "*****@*****.**",
                CC = ""
            };
            LoggingRule mailInfo = new LoggingRule("*", NLog.LogLevel.Info, mailTarget);

            config.LoggingRules.Add(mailInfo);

            //===========================================================================================//
            DatabaseTarget dbTarget = new DatabaseTarget();

            //===========================================================================================//

            // Step 4. Define rules
            LogManager.Configuration = config;
        }
Esempio n. 30
0
        public WorkerRole(Settings settings)
        {
            string logDir = Path.Combine(Environment.CurrentDirectory, "Logs");

            try
            {
                // Configure NLog
                LoggingConfiguration config = new LoggingConfiguration();

                // Console Target
                var consoleTarget = new SnazzyConsoleTarget();
                config.AddTarget("console", consoleTarget);
                consoleTarget.Layout = "[${logger:shortName=true}] ${message}";

                // Get the logs resource if it exists and use it as the log dir
                try
                {
                    if (RoleEnvironment.IsAvailable)
                    {
                        LocalResource logsResource = RoleEnvironment.GetLocalResource("Logs");
                        logDir = logsResource.RootPath;
                    }
                }
                catch (Exception)
                {
                    // Just use basedir.
                }

                // File Target
                FileTarget jobLogTarget = new FileTarget()
                {
                    FileName        = Path.Combine(logDir, "Jobs", "${logger:shortName=true}.log.json"),
                    ArchiveFileName = Path.Combine(logDir, "Jobs", "${logger:shortName=true}.${date:yyyy-MM-dd}.log")
                };
                ConfigureFileTarget(jobLogTarget);
                config.AddTarget("file-job", jobLogTarget);
                FileTarget hostTarget = new FileTarget()
                {
                    FileName        = Path.Combine(logDir, "Host", "Host.log.json"),
                    ArchiveFileName = Path.Combine(logDir, "Host", "Host.${date:yyyy-MM-dd}.log")
                };
                ConfigureFileTarget(hostTarget);
                config.AddTarget("file-host", hostTarget);
                FileTarget globalTarget = new FileTarget()
                {
                    FileName = Path.Combine(logDir, "Master", "Master.log.json")
                };
                ConfigureFileTarget(globalTarget);
                globalTarget.MaxArchiveFiles        = 1;
                globalTarget.ArchiveAboveSize       = 1024 * 1024;
                globalTarget.EnableFileDelete       = true;
                globalTarget.DeleteOldFileOnStartup = true;
                globalTarget.AutoFlush = true;
                config.AddTarget("file-master", globalTarget);

                TraceTarget traceTarget = new TraceTarget()
                {
                    Layout = "[${logger:shortName=true}][${date:yyyy-MM-ddTHHmmss}]${message}"
                };
                config.AddTarget("trace", traceTarget);

                LoggingRule allMessagesToConsole = new LoggingRule("*", NLog.LogLevel.Trace, consoleTarget);
                config.LoggingRules.Add(allMessagesToConsole);
                LoggingRule allMessagesToGlobal = new LoggingRule("*", NLog.LogLevel.Debug, globalTarget);
                config.LoggingRules.Add(allMessagesToGlobal);
                LoggingRule allMessagesToTrace = new LoggingRule("*", NLog.LogLevel.Debug, traceTarget);
                config.LoggingRules.Add(allMessagesToTrace);

                // All other rules transfer all kinds of log messages EXCEPT Trace.
                LoggingRule hostToFile = new LoggingRule("JobRunner", NLog.LogLevel.Debug, hostTarget);
                config.LoggingRules.Add(hostToFile);

                LoggingRule roleToFile = new LoggingRule("WorkerRole", NLog.LogLevel.Debug, hostTarget);
                config.LoggingRules.Add(roleToFile);

                LoggingRule jobLogs = new LoggingRule("Job.*", NLog.LogLevel.Debug, jobLogTarget);
                config.LoggingRules.Add(jobLogs);

                LogManager.Configuration = config;

                _logger = LogManager.GetLogger("WorkerRole");
            }
            catch (Exception ex)
            {
                File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FatalError.txt"), ex.ToString());
            }

            _logger.Info("Logging Enabled to {0}", logDir);

            try
            {
                if (RoleEnvironment.IsAvailable)
                {
                    ConfigureAzureDiagnostics(logDir);
                }
                else
                {
                    _logger.Info("Skipping Azure Diagnostics, we aren't in Azure");
                }
            }
            catch (Exception ex)
            {
                _logger.InfoException("Skipping Azure Diagnostics, we got an exception trying to check if we are in Azure", ex);
            }

            try
            {
                _runner = LoadJobRunner(settings);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error loading Job Runner", ex);
            }
        }
Esempio n. 31
0
 public TraceOn(TraceTarget traceTarget)
 {
     Target = traceTarget;
 }
Esempio n. 32
0
File: WDNav.cs Progetto: subha9/WDTF
        public AutomationLogging()
        {
            string resultFolder = @"C:/WDTF/TestResult";
            string asm          = Assembly.GetCallingAssembly().FullName;
            string logFormat    = string.Format("{0:yyMMddhhmmss}", DateTime.Now);

            newLocationInResultFolder = resultFolder + "/" + currentGuid + "_" + logFormat;
            DirectoryInfo directoryInfo = new DirectoryInfo(newLocationInResultFolder);

            if (!directoryInfo.Exists)
            {
                System.IO.Directory.CreateDirectory(newLocationInResultFolder);
            }
            //FileInfo[] fileInformation = directoryInfo.GetFiles();
            //foreach (FileInfo item in fileInformation)
            //{
            //    item.Delete();
            //}
            LoggingConfiguration config = new LoggingConfiguration();
            //{TestName}_TIME.htm
            // string logFormat = string.Format("{0:yyMMddhhmmss}", DateTime.Now);


            //===========================================================================================//
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();

            consoleTarget.Layout = "${time} | ${level}  | ${stacktrace::topFrames=2}|${message} ";
            config.AddTarget("console", consoleTarget);
            LoggingRule consoleInfo = new LoggingRule("*", LogLevel.Info, consoleTarget);

            config.LoggingRules.Add(consoleInfo);
            //===========================================================================================//
            FileTarget fileTarget = new FileTarget();

            fileTarget.Layout   = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ";
            fileTarget.FileName = newLocationInResultFolder + "/" + className + "_" + logFormat + ".txt";
            config.AddTarget("file", fileTarget);
            LoggingRule fileInfo = new LoggingRule("*", LogLevel.Info, fileTarget);

            config.LoggingRules.Add(fileInfo);
            //===========================================================================================//
            TraceTarget traceTarget = new TraceTarget();

            traceTarget.Layout = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ";

            //===========================================================================================//
            MailTarget mailTarget = new MailTarget();

            mailTarget.Name               = "gmail";
            mailTarget.SmtpServer         = "smtp.gmail.com";
            mailTarget.SmtpPort           = 465;
            mailTarget.SmtpAuthentication = SmtpAuthenticationMode.Basic;
            mailTarget.SmtpUserName       = "******";
            mailTarget.SmtpPassword       = "******";
            mailTarget.EnableSsl          = true;
            mailTarget.From               = "*****@*****.**";
            mailTarget.To = "*****@*****.**";
            mailTarget.CC = "";
            LoggingRule mailInfo = new LoggingRule("*", LogLevel.Info, mailTarget);

            config.LoggingRules.Add(mailInfo);

            //===========================================================================================//
            DatabaseTarget dbTarget = new DatabaseTarget();

            //===========================================================================================//

            // Step 4. Define rules
            LogManager.Configuration = config;
        }