Пример #1
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;
        }
Пример #2
0
        public void UsingNLog()
        {
            var writer = GetTrace();

            LoggingConfiguration config = new LoggingConfiguration();

            TraceTarget target = new TraceTarget();
            target.Layout = "NLOG [${level:uppercase=true}] ${message}";
            config.AddTarget("trace", target);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, target));

            LogManager.Configuration = config;

            ConventionBuilder.Logger = t => LogManager.GetLogger(t);

            var builder = new ConventionBuilder();
            builder.ScanThisAssembly().For<HandlerConventions>();

            var convention = builder.Build();

            Approvals.VerifyAll(writer
                .ToString()
                .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                .OrderBy(s => s), "");
        }
Пример #3
0
        private async Task<bool> OnStartCore()
        {
            _current = this;

            // Set up logging
            LoggingConfiguration logConfig = new LoggingConfiguration();
            var fileTarget = new FileTarget()
            {
                Layout = "[${logger}](${date}) ${message}",
                FileName = Path.Combine(RoleEnvironment.GetLocalResource("ConsulLogs").RootPath, "Consulate.log")
            };
            var traceTarget = new TraceTarget()
            {
                Layout = "[${logger}] ${message}"
            };
            logConfig.AddTarget("file", fileTarget);
            logConfig.AddTarget("trace", traceTarget);

            logConfig.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Trace, fileTarget));
            logConfig.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Trace, traceTarget));
            LogManager.Configuration = logConfig;

            // Create config
            var config = new ConsulConfig()
            {
                NodeName = RoleEnvironment.CurrentRoleInstance.Id,
                DataDir = RoleEnvironment.GetLocalResource("ConsulData").RootPath,
                BindAddr = GetIP("Consul.Rpc"),
                ClientAddr = GetIP("Consul.Rpc"),
                Ports = new ConsulPorts()
                {
                    Dns = GetPort("Consul.Dns"),
                    Http = GetPort("Consul.Http"),
                    Rpc = GetPort("Consul.Rpc"),
                    SerfLan = GetPort("Consul.SerfLan"),
                    SerfWan = GetPort("Consul.SerfWan"),
                    Server = GetPort("Consul.Server")
                }
            };

            var clients = GetClients();

            // Step 1 - Poll for an existing cluster
            Log.Info("Searching for cluster...");
            var existingCluster = await FindExistingCluster(clients);

            if (!existingCluster.Any())
            {
                Log.Info("No cluster found, attempting to bootstrap one!");
                _agent = await Bootstrap(clients, config);
            }
            else
            {
                Log.Info("Found a cluster! Joining it");
                _agent = await Join(config, existingCluster);
            }
            return true;
        }
Пример #4
0
 public void PrepareLogging()
 {
     var config = new LoggingConfiguration();
     var debugTarget = new TraceTarget {
         Layout = "${level:uppercase=true:padding=-8} ${message}"
     };
     config.AddTarget("Debug", debugTarget);
     var rule = new LoggingRule("*", LogLevel.Debug, debugTarget);
     config.LoggingRules.Add(rule);
     LogManager.Configuration = config;
 }
Пример #5
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");
    }
Пример #6
0
        public ValidationTests()
        {
            LoggingConfiguration config = new LoggingConfiguration();

            TraceTarget target = new TraceTarget();
            target.Layout = "NLOG [${level:uppercase=true}] ${message}";
            config.AddTarget("trace", target);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, target));

            LogManager.Configuration = config;

            ConventionBuilder.Logger = t => LogManager.GetLogger(t);
        }
Пример #7
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);
            }
        }
Пример #8
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);
                }
            }
        }
Пример #9
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());
        }