public NLogLogProviderLoggingEnabledTests() { NLogLogManager.ProviderIsAvailableOverride = true; var config = new LoggingConfiguration(); simpleLayoutTarget = new MemoryTarget { Layout = "${level:uppercase=true}|${message}|${exception}" }; ndcLayoutTarget = new MemoryTarget { Layout = "${level:uppercase=true}|${ndc:bottomFrames=10:topFrames=10:separator=;}|${message}|${exception}" }; mdcLayoutTarget = new MemoryTarget { Layout = "${level:uppercase=true}|${mdc:item=Key}|${message}|${exception}" }; config.AddTarget("simpleLayoutMemory", simpleLayoutTarget); config.AddTarget("mdcLayoutTarget", mdcLayoutTarget); config.AddTarget("ndcLayoutMemory", ndcLayoutTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, simpleLayoutTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, mdcLayoutTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, ndcLayoutTarget)); LogManager.Configuration = config; nLogLogManager = new NLogLogManager(); sut = nLogLogManager.GetLogger("Test"); }
private static void InitLogging() { var s_Config = new LoggingConfiguration(); var s_ConsoleTarget = new ColoredConsoleTarget(); s_Config.AddTarget("console", s_ConsoleTarget); s_ConsoleTarget.Layout = @"[${date:format=HH\:mm\:ss.fff}] ${logger} >> ${message}"; var s_ConsoleRule = new LoggingRule("*", LogLevel.Trace, s_ConsoleTarget); s_Config.LoggingRules.Add(s_ConsoleRule); var s_FileTarget = new FileTarget(); s_Config.AddTarget("file", s_FileTarget); s_FileTarget.FileName = "${basedir}/GrooveCaster.log"; s_FileTarget.Layout = @"[${date:format=HH\:mm\:ss.fff}] ${logger} >> ${message}"; s_FileTarget.ArchiveFileName = "${basedir}/GrooveCaster.{#}.log"; s_FileTarget.ArchiveEvery = FileArchivePeriod.Day; s_FileTarget.ArchiveNumbering = ArchiveNumberingMode.Date; s_FileTarget.ArchiveDateFormat = "yyyMMdd"; var s_FileRule = new LoggingRule("*", LogLevel.Trace, s_FileTarget); s_Config.LoggingRules.Add(s_FileRule); LogManager.Configuration = s_Config; }
public 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 new AsyncTargetWrapper().Wrap(); // 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; }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { #if DNX451 var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = @"${date:format=HH\\:MM\\:ss} ${ndc} ${logger} ${message} "; var rule1 = new LoggingRule("*", NLog.LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule1); loggerFactory.AddNLog(new global::NLog.LogFactory(config)); #endif app.UseErrorPage() .UseStaticFiles() .UseIdentity() .UseFacebookAuthentication() .UseGoogleAuthentication() .UseTwitterAuthentication() .UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); }); //Populates the Admin user and role SampleData.InitializeIdentityDatabaseAsync(app.ApplicationServices).Wait(); }
public ExamplePrograms() { var loggerNamePattern = "BitSharp.Examples.*"; var logLevel = LogLevel.Info; // log layout format var layout = "${message} ${exception:separator=\r\n:format=message,type,method,stackTrace:maxInnerExceptionLevel=10:innerExceptionSeparator=\r\n:innerFormat=message,type,method,stackTrace}"; // initialize logging configuration var config = new LoggingConfiguration(); // create console target var consoleTarget = new ColoredConsoleTarget(); consoleTarget.Layout = layout; config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule(loggerNamePattern, logLevel, consoleTarget)); // create debugger target, if attached if (Debugger.IsAttached) { var debuggerTarget = new DebuggerTarget(); debuggerTarget.Layout = layout; config.AddTarget("debugger", debuggerTarget); config.LoggingRules.Add(new LoggingRule(loggerNamePattern, logLevel, debuggerTarget)); } LogManager.Configuration = config; logger = LogManager.GetCurrentClassLogger(); }
private void BuildNlogConfig() { LoggingConfiguration config = new LoggingConfiguration(); // Create targets ConsoleTarget consoleTarget = new ConsoleTarget(); config.AddTarget("console", consoleTarget); FileTarget fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); //memoryTarget = new MemoryTarget(); //config.AddTarget("memory", memoryTarget); // define layout consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${level} ${logger} ${message}"; fileTarget.FileName = System.IO.Path.Combine(System.IO.Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "monotorrent"), "monotorrent.log"); fileTarget.Layout = "${level} ${stacktrace} ${message}"; //memoryTarget.Layout = "${date:format=HH\\:MM\\:ss} ${level} ${logger} ${message}"; // define rules LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule1); LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule2); //LoggingRule rule3 = new LoggingRule("*", LogLevel.Debug, fileTarget); //config.LoggingRules.Add(rule3); LogManager.Configuration = config; }
protected override LoggingConfiguration SetupLogging(EndpointConfiguration endpointConfiguration) { var logDir = ".\\logfiles\\"; Directory.CreateDirectory(logDir); var logFile = Path.Combine(logDir, endpointConfiguration.EndpointName + ".txt"); if (File.Exists(logFile)) { File.Delete(logFile); } var logLevel = "ERROR"; var nlogConfig = new LoggingConfiguration(); var fileTarget = new FileTarget { FileName = logFile, }; nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Warn, fileTarget) { Final = true }); nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(logLevel), fileTarget)); nlogConfig.LoggingRules.Add(new LoggingRule("ServiceControl.ExternalIntegrations.*", LogLevel.Debug, fileTarget)); nlogConfig.AddTarget("debugger", fileTarget); NLogConfigurator.Configure(new object[] { fileTarget }, logLevel); return nlogConfig; }
protected virtual LoggingConfiguration SetupLogging(EndpointConfiguration endpointConfiguration) { var logDir = ".\\logfiles\\"; Directory.CreateDirectory(logDir); var logFile = Path.Combine(logDir, endpointConfiguration.EndpointName + ".txt"); if (File.Exists(logFile)) { File.Delete(logFile); } var logLevel = "INFO"; var nlogConfig = new LoggingConfiguration(); var fileTarget = new FileTarget { FileName = logFile, Layout = "${longdate}|${level:uppercase=true}|${threadid}|${logger}|${message}${onexception:inner=${newline}${exception}${newline}${stacktrace:format=DetailedFlat}}" }; nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Warn, fileTarget) { Final = true }); nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(logLevel), fileTarget)); nlogConfig.AddTarget("debugger", fileTarget); NLogConfigurator.Configure(new object[] {fileTarget}, logLevel); return nlogConfig; }
public static void Configure() { // 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); // Step 3. Set target properties consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}"; fileTarget.FileName = "${basedir}/SimplePerformanceMeter.txt"; fileTarget.Layout = "${message}"; // Step 4. Define rules var rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule2); // Step 5. Activate the configuration LogManager.Configuration = config; }
private void ConfigLogging() { var config = new LoggingConfiguration(); var target = new DebuggerTarget { Layout = @"${date:format=HH\\:MM\\:ss} ${logger} ${message}" }; var sqlTarget = new FileTarget { Layout = @"${date:format=HH\\:MM\\:ss} ${logger} ${message}", FileName = "sql.log" }; var rule = new LoggingRule( "*", LogLevel.Trace, target ); var sqlRule = new LoggingRule( "NHibernate", LogLevel.Trace, sqlTarget ); config.AddTarget( "sql", sqlTarget ); config.AddTarget( "debugger", target ); config.LoggingRules.Add( sqlRule ); config.LoggingRules.Add( rule ); LogManager.Configuration = config; }
/// <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; }
public override void Load() { // log layout format var layout = "${date:format=hh\\:mm\\:ss tt} ${pad:padding=6:inner=${level:uppercase=true}} ${message} ${exception:separator=\r\n:format=message,type,method,stackTrace:maxInnerExceptionLevel=10:innerExceptionSeparator=\r\n:innerFormat=message,type,method,stackTrace}"; // initialize logging configuration var config = new LoggingConfiguration(); // create debugger target var debuggerTarget = new DebuggerTarget(); debuggerTarget.Layout = layout; config.AddTarget("console", debuggerTarget); config.LoggingRules.Add(new LoggingRule("*", logLevel, WrapAsync(debuggerTarget))); // create file target var fileTarget = new FileTarget() { AutoFlush = false }; fileTarget.Layout = layout; fileTarget.FileName = Path.Combine(this.directory, "BitSharp.log"); fileTarget.DeleteOldFileOnStartup = true; config.AddTarget("file", fileTarget); config.LoggingRules.Add(new LoggingRule("*", logLevel, WrapAsync(fileTarget))); // activate configuration and bind LogManager.Configuration = config; }
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), ""); }
private void ConfigureLogging() { var fileTarget = new FileTarget { FileName = Path.Combine(GetLogFolder(), "log.xml"), ArchiveFileName = "log_{#####}.xml", ArchiveNumbering = ArchiveNumberingMode.Sequence, ArchiveAboveSize = 1024*1024, Layout = new Log4JXmlEventLayout() }; var config = new LoggingConfiguration(); config.AddTarget("file", fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); var debuggerTarget = new DebuggerTarget(); config.AddTarget("debugger", debuggerTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, debuggerTarget)); if (Debugger.IsAttached) { var udpTarget = new NetworkTarget { Address = "udp4://localhost:962", Layout = new Log4JXmlEventLayout() }; config.AddTarget("udp", udpTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, udpTarget)); } LogManager.Configuration = config; PresentationTraceSources.DataBindingSource.Listeners.Add(new NLogTraceListener()); }
// ------------------------------------------ // Logs Management // ------------------------------------------ protected void SetupLogging() { var path = ConfigManager.GetInstance().Find("debug.log-file", null); if (null == path) { return; } LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget(); consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; config.AddTarget("console", consoleTarget); FileTarget fileTarget = new FileTarget(); fileTarget.FileName = path; fileTarget.Layout = "${message}"; fileTarget.CreateDirs = true; config.AddTarget("file", fileTarget); LoggingRule rule1 = new LoggingRule("*", LogLevel.Info, consoleTarget); config.LoggingRules.Add(rule1); LoggingRule rule2 = new LoggingRule("*", LogLevel.Info, fileTarget); config.LoggingRules.Add(rule2); LoggingRule rule3 = new LoggingRule("*", LogLevel.Warn, consoleTarget); config.LoggingRules.Add(rule3); LoggingRule rule4 = new LoggingRule("*", LogLevel.Warn, fileTarget); config.LoggingRules.Add(rule4); // Ready LogManager.ReconfigExistingLoggers(); LogManager.Configuration = config; Host.Log(this, "STARTING LOGGING:" + fileTarget.FileName); }
public NLogLogger() { ConfigurationItemFactory.Default.RegisterItemsFromAssembly(Assembly.GetExecutingAssembly()); var config = new LoggingConfiguration(); //var consoleTarget = new ColoredConsoleTarget(); //config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget)); var elasticTarget = new BufferingTargetWrapper(new ElasticSearchTarget { Fields = { new ElasticSearchField { Name = "application", Layout = "LoggerAppNLog" }, new ElasticSearchField { Name = "machinename", Layout = "${machinename}" }, } }, 1000, 1000); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, elasticTarget)); LogManager.Configuration = config; }
private static void Main(string[] args) { if (args.Length <= 0) { return; } var config = new LoggingConfiguration(); var logfile = new FileTarget(); var logdir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HearthstoneTracker"); logdir = Path.Combine(logdir, "logs"); var logfilename = Path.Combine(logdir, "updater.${date:format=yyyy-MM-dd}.txt"); logfile.FileName = logfilename; logfile.CreateDirs = true; logfile.MaxArchiveFiles = 7; logfile.ArchiveEvery = FileArchivePeriod.Day; logfile.ConcurrentWrites = true; logfile.Layout = "${longdate}|${level:uppercase=true}|thread:${threadid}|${logger}|${message}${onexception:inner=${newline}${exception:format=tostring}}"; config.AddTarget("logfile", logfile); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, logfile)); LogManager.Configuration = config; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new UpdateProgress(args)); }
/// <summary> /// Constructs an instance of DependencyRegistry /// </summary> public DependencyRegistry(ConfigSettings configSettings) { string logFileTemplate = configSettings.LogFileTemplate ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "default.log"); string dataDirectory = configSettings.DataDirectory ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "configdata"); LogLevel logLevel = GetMatchingLogLevelOrDefault(configSettings.LogLevel) ?? LogLevel.Info; For<IRepository<IJsonEntity<ConfigRoot>>>() .Singleton() .Use(new DurableMemoryRepository<ConfigRoot>(dataDirectory, new FileSystemFacade())); var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); fileTarget.Name = "LogFile"; fileTarget.FileName = logFileTemplate; config.AddTarget(fileTarget.Name, fileTarget); var loggingRule = new LoggingRule("*", logLevel, fileTarget); config.LoggingRules.Add(loggingRule); LogManager.Configuration = config; For<ILogger>() .Singleton() .Use(l => new LoggerAdapter(LogManager.GetLogger(GetType().Namespace))); // Ask StructureMap to always do property injection for certain properties // TODO: remove this? SetAllProperties(policy => policy.OfType<ILogger>()); }
public static void SetupLogging(LogLevel logLevel) { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var debuggerTarget = new DebuggerTarget(); config.AddTarget("debugger", debuggerTarget); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); // Step 3. Set target properties debuggerTarget.Layout = @"${logger:shortName=True} - ${uppercase:${level}}: ${message}"; fileTarget.FileName = "${specialfolder:folder=MyDocuments}/Artemis/logs/${shortdate}.txt"; fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}"; fileTarget.EnableFileDelete = true; fileTarget.MaxArchiveFiles = 7; fileTarget.ArchiveEvery = FileArchivePeriod.Minute; // Step 4. Define rules var rule1 = new LoggingRule("*", logLevel, debuggerTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", logLevel, fileTarget); config.LoggingRules.Add(rule2); // Step 5. Activate the configuration LogManager.Configuration = config; // Log as fatal so it always shows var logger = LogManager.GetCurrentClassLogger(); logger.Fatal("INFO: Set log level to {0}", logLevel); }
public static void LoadLoggerToLoggingConfig(LoggingConfiguration logConfig, IConfiguration Configuration,string sectionString) { var fileLoggerSection = Configuration.GetSection(sectionString).GetChildren(); foreach (var logging in fileLoggerSection) { var target = new FileTarget() { FileName = logging["fileName"], Name = logging["name"], Layout = logging["layoutFormat"] }; var minLevel = logging["minLevel"] != null ? LogLevel.FromString(logging["minLevel"]) : null; LoggingRule rule = null; if (minLevel != null) { rule = new LoggingRule(logging["namePattern"], minLevel, target); } else { rule = new LoggingRule(logging["namePattern"], target); } var useLevels = logging["logLevel"]; if(string.IsNullOrWhiteSpace(useLevels) == false) { var levels = useLevels.Split(','); foreach (var level in levels) { rule.EnableLoggingForLevel(LogLevel.FromString(level)); } } logConfig.AddTarget(target); logConfig.LoggingRules.Add(rule); } }
/* Configure the logger programmatically. */ static NLoggerUtil() { var config = new LoggingConfiguration(); string path = "GhostFactor.log"; if (toDesktop) path = desktopPath + path; var target = new FileTarget { FileName = path }; // Add a file target where all the log shall go to. config.AddTarget("file", target); // Add a rule that any information higher than debug goes to the file. var rule = new LoggingRule("*", LogLevel.Debug, target); config.LoggingRules.Add(rule); // Also log fatal logs to another file. string fatalPath = "GhostFactorFatal.log"; if (toDesktop) fatalPath = desktopPath + fatalPath; var fatalTarget = new FileTarget() { FileName = fatalPath }; var fatalRule = new LoggingRule("*", LogLevel.Fatal, fatalTarget); config.LoggingRules.Add(fatalRule); LogManager.Configuration = config; }
private void SetupLogging() { LoggingConfiguration configuration = new LoggingConfiguration(); NLogViewerTarget log_viewer_target = new NLogViewerTarget(); configuration.AddTarget("viewer", log_viewer_target); log_viewer_target.Name = "viewer"; log_viewer_target.Address = "udp://127.0.0.1:9999"; LoggingRule log_viewer_rule = new LoggingRule("*", LogLevel.Trace, log_viewer_target); configuration.LoggingRules.Add(log_viewer_rule); if (!string.IsNullOrEmpty(LogFile)) { FileTarget file_target = new FileTarget(); configuration.AddTarget("file", file_target); file_target.FileName = LogFile; file_target.Layout = "${message}"; file_target.DeleteOldFileOnStartup = true; LoggingRule log_file_rule = new LoggingRule("*", LogLevel.Trace, file_target); configuration.LoggingRules.Add(log_file_rule); } // Step 5. Activate the configuration LogManager.Configuration = configuration; }
internal InitializeContext(LoggingConfiguration cfg, bool throwExceptions) { _cfg = cfg; _throwExceptions = throwExceptions; _visited = new HashSet<object>(); _initialized = new List<ISupportsInitialize>(); }
public override void Load() { // log layout format var layout = "${date:format=hh\\:mm\\:ss tt} ${pad:padding=6:inner=${level:uppercase=true}} ${message} ${exception:separator=\r\n:format=message,type,method,stackTrace:maxInnerExceptionLevel=10:innerExceptionSeparator=\r\n:innerFormat=message,type,method,stackTrace}"; // initialize logging configuration var config = new LoggingConfiguration(); // create console target if (!Debugger.IsAttached) { var consoleTarget = new ColoredConsoleTarget(); consoleTarget.Layout = layout; config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", this.logLevel, consoleTarget)); } else { var consoleTarget = new DebuggerTarget(); consoleTarget.Layout = layout; config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", this.logLevel, consoleTarget)); } // activate configuration and bind LogManager.Configuration = config; }
public static void Configure() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); fileTarget.FileName = Path.Combine(Util.get_log_folder(), "btnet_log.txt"); fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date; fileTarget.ArchiveEvery = FileArchivePeriod.Day; config.AddTarget("File", fileTarget); var mailTarget = new MailTarget { UseSystemNetMailSettings = true, To = Util.get_setting("ErrorEmailTo", ""), From = Util.get_setting("ErrorEmailFrom", ""), Subject = "BTNET Error Notification", Layout = "${machinename}${newline} ${date} ${newline} ${newline} ${message} ${newline} ${exception} ${newline}" }; config.AddTarget("Mail", mailTarget); //Turn logging on/off based on the LogEnabled setting var logLevel = Util.get_setting("LogEnabled", "1") == "1" ? LogLevel.Trace: LogLevel.Off; config.LoggingRules.Add(new LoggingRule("*", logLevel, fileTarget)); var emailLogLevel = Util.get_setting("ErrorEmailEnabled", "1") == "1" ? LogLevel.Fatal : LogLevel.Off; config.LoggingRules.Add(new LoggingRule("*", emailLogLevel, mailTarget)); LogManager.Configuration = config; }
public void UsingLoggingAspectWithNLogShouldUseNlogger() { // arrange - setup nlog LoggingConfiguration config = new LoggingConfiguration(); MemoryTarget memoryTarget = new MemoryTarget { Layout = @"${message}" }; config.AddTarget("memory", memoryTarget); LoggingRule rule = new LoggingRule("*", LogLevel.Debug, memoryTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; Mock<IConfigurationProvider> mock = new Mock<IConfigurationProvider>(); mock.Setup(provider => provider.ShouldLog(It.IsAny<LogAttribute>())).Returns(true); LogAttribute.ConfigurationProvider = mock.Object; // arrange - setup logger LogAttribute.Logger = new NLogLogger("memory"); // act Person person = new Person { Name = "test", Balance = 0.0d }; person.Should().NotBeNull(); // assert memoryTarget.Logs.Count.Should().Be(9, "because we called the logging 9 times"); }
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; }
private static Logger SetupNLog(NLogConfigurationApi config) { var logDirectory = string.IsNullOrEmpty(config.LogDirectory) ? "${basedir}/Logs" : config.LogDirectory; var fileTarget = new FileTarget { Name = "FileTarget", Layout = "${message}", ConcurrentWrites = false, FileName = new SimpleLayout(Path.Combine(logDirectory, "current.log")), ArchiveEvery = config.ArchivePeriod, ArchiveNumbering = ArchiveNumberingMode.Sequence, MaxArchiveFiles = config.MaxArchiveFiles, ArchiveFileName = new SimpleLayout(Path.Combine(logDirectory,"archive/{####}.log")) }; var asyncWrapper = new AsyncTargetWrapper(fileTarget) { Name = "AsyncWrapper" }; var loggingConfiguration = new LoggingConfiguration(); loggingConfiguration.AddTarget(LoggerName, asyncWrapper); loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LevelToNLogLevel(config.MinimumLogLevel), asyncWrapper)); LogManager.Configuration = loggingConfiguration; return LogManager.GetLogger(LoggerName); }
public static void UseNLog(this IHost host) { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); var layout = @"${longdate}|${level:uppercase=true}|${threadid}|${logger}|${message}"; consoleTarget.Layout = layout; fileTarget.FileName = @"${tempdir}\${processname}\Log\${processname}.${processinfo:Id}.log"; fileTarget.ArchiveFileName = @"${tempdir}\${processname}\Log\${processname}.${processinfo:Id}.{###}.log"; fileTarget.ArchiveEvery = FileArchivePeriod.Day; fileTarget.ArchiveAboveSize = 1024000; fileTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling; fileTarget.MaxArchiveFiles = 10; fileTarget.ConcurrentWrites = false; fileTarget.KeepFileOpen = false; fileTarget.Layout = layout; config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Debug, consoleTarget)); config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Info, fileTarget)); LogManager.Configuration = config; host.Container.RegisterType(typeof (ILogger<>), typeof (NLogger<>)); }
private static void ConfigureFileTarget(LoggingConfiguration config) { //TODO: code missing if(Testing.IsTestRunning() /*|| !Settings.Settings.Get<Settings.Settings>().FileLog*/) { return; } var assembly = AssemblyUtils.GetEntryAssembly(); var fileTarget = new FileTarget { FileName = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "Log", $"{DateTime.Now.ToString("yyyy-MM-dd")} - {assembly.GetName().Name}.log"), Layout = LogLayout }; config.AddTarget("file", fileTarget); var fileTargetRule = new LoggingRule("*", LogLevel.Trace, fileTarget); config.LoggingRules.Add(fileTargetRule); Trace.WriteLine($"Registering Log file: {fileTarget.FileName}"); }
/** * Configures the Console/File logging. * * TODO: make it configurable (log levels, file name). */ public static void ConfigureLogging() { var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "app.log" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); NLog.LogManager.Configuration = config; }
private void SetUpNLog() { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "backupclientlogfile_helperservice.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole); config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logfile); // Apply config LogManager.Configuration = config; _logger = LogManager.GetCurrentClassLogger(); }
public void TestDualClientWithoutTor() { using (NodeBuilder builder = NodeBuilder.Create(version: "0.15.1")) { HttpClient client = null; var coreNode = builder.CreateNode(false); coreNode.ConfigParameters.AddOrReplace("debug", "1"); coreNode.ConfigParameters.AddOrReplace("printtoconsole", "0"); coreNode.ConfigParameters.AddOrReplace("prematurewitness", "1"); coreNode.ConfigParameters.AddOrReplace("walletprematurewitness", "1"); coreNode.ConfigParameters.AddOrReplace("rpcworkqueue", "100"); coreNode.Start(); // Replicate portions of BreezeServer's Program.cs. Maybe refactor it into a class/function in future var serviceProvider = new ServiceCollection() .AddLogging() .AddSingleton <Breeze.BreezeServer.Services.ITumblerService, Breeze.BreezeServer.Services.TumblerService>() .BuildServiceProvider(); serviceProvider .GetService <ILoggerFactory>() .AddConsole(LogLevel.Debug); // Skip the registration code - that can be tested separately string configPath = Path.Combine(coreNode.DataFolder, "breeze.conf"); string[] breezeServerConfig = { "network=regtest", // Only the network setting is currently used from this file "rpc.user=dummy", "rpc.password=dummy", "rpc.url=http://127.0.0.1:26174/", "breeze.ipv4=127.0.0.1", "breeze.ipv6=2001:0db8:85a3:0000:0000:8a2e:0370:7334", "breeze.onion=0123456789ABCDEF", "breeze.port=37123", "breeze.regtxfeevalue=10000", "breeze.regtxoutputvalue=1000", "tumbler.url=http://127.0.0.1:37123/api/v1/", "tumbler.rsakeyfile=/Users/username/.ntumblebitserver/RegTest/Tumbler.pem", "tumbler.ecdsakeyaddress=TVwRFmEKRCnQAgShf3QshBjp1Tmucm1e87" }; File.WriteAllLines(configPath, breezeServerConfig); BreezeConfiguration config = new BreezeConfiguration(configPath); var rpc3 = coreNode.CreateRPCClient(); string ntbServerConfigPath = Path.Combine(coreNode.DataFolder, "server.config"); string[] ntbServerConfig = { "regtest=1", "rpc.url=http://127.0.0.1:" + rpc3.Address.Port + "/", "rpc.user="******"rpc.password="******"cycle=kotori", "tor.enabled=false" }; File.WriteAllLines(ntbServerConfigPath, ntbServerConfig); // We need to start up the masternode prior to creating the SBFN instance so that // we have the URI available for starting the TumbleBit feature // TODO: Also need to see if NTB interactive console interferes with later parts of the test new Thread(delegate() { Thread.CurrentThread.IsBackground = true; // By instantiating the TumblerService directly the registration logic is skipped var tumbler = serviceProvider.GetService <Breeze.BreezeServer.Services.ITumblerService>(); tumbler.StartTumbler(config, false, "server.config", Path.GetFullPath(coreNode.DataFolder), false); }).Start(); // Wait for URI file to be written out by the TumblerService while (!File.Exists(Path.Combine(coreNode.DataFolder, "uri.txt"))) { Thread.Sleep(1000); } Console.WriteLine("* URI file detected *"); Thread.Sleep(5000); var serverAddress = File.ReadAllText(Path.Combine(coreNode.DataFolder, "uri.txt")); // Not used for this test ConfigurationOptionWrapper <string> registrationStoreDirectory = new ConfigurationOptionWrapper <string>("RegistrationStoreDirectory", ""); // Force SBFN to use the temporary hidden service to connect to the server ConfigurationOptionWrapper <string> masternodeUri = new ConfigurationOptionWrapper <string>("MasterNodeUri", serverAddress); ConfigurationOptionWrapper <string>[] configurationOptions = { registrationStoreDirectory, masternodeUri }; // Logging for NTB client code ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor(); Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(true), false, loggerProcessor))); CoreNode node1 = builder.CreateStratisPowNode(false, fullNodeBuilder => { fullNodeBuilder .UseConsensus() .UseBlockStore() .UseMempool() .UseBlockNotification() .UseTransactionNotification() .AddMining() .UseWallet() .UseWatchOnlyWallet() .UseApi() .AddRPC() .UseTumbleBit(configurationOptions); }); node1.ConfigParameters.AddOrReplace("apiuri", "http://localhost:37229"); CoreNode node2 = builder.CreateStratisPowNode(false, fullNodeBuilder => { fullNodeBuilder .UseConsensus() .UseBlockStore() .UseMempool() .UseBlockNotification() .UseTransactionNotification() .AddMining() .UseWallet() .UseWatchOnlyWallet() .UseApi() .AddRPC() .UseTumbleBit(configurationOptions); }); node2.ConfigParameters.AddOrReplace("apiuri", "http://localhost:37228"); var apiSettings1 = node1.FullNode.NodeService <ApiSettings>(); var apiSettings2 = node2.FullNode.NodeService <ApiSettings>(); node1.Start(); node2.Start(); // TODO: See if it is possible to split node1 and node2's logs into separate folders NLog.Config.LoggingConfiguration config1 = LogManager.Configuration; var folder = Path.Combine(node1.DataFolder, "Logs"); var tbTarget = new FileTarget(); tbTarget.Name = "tumblebit"; tbTarget.FileName = Path.Combine(folder, "tumblebit.txt"); tbTarget.ArchiveFileName = Path.Combine(folder, "tb-${date:universalTime=true:format=yyyy-MM-dd}.txt"); tbTarget.ArchiveNumbering = ArchiveNumberingMode.Sequence; tbTarget.ArchiveEvery = FileArchivePeriod.Day; tbTarget.MaxArchiveFiles = 7; tbTarget.Layout = "[${longdate:universalTime=true} ${threadid}${mdlc:item=id}] ${level:uppercase=true}: ${callsite} ${message}"; tbTarget.Encoding = Encoding.UTF8; var ruleTb = new LoggingRule("*", NLog.LogLevel.Debug, tbTarget); config1.LoggingRules.Add(ruleTb); config1.AddTarget(tbTarget); // Apply new rules. LogManager.ReconfigExistingLoggers(); node1.NotInIBD(); node2.NotInIBD(); // Create the source and destination wallets for node 1 var wm1 = node1.FullNode.NodeService <IWalletManager>() as WalletManager; wm1.CreateWallet("TumbleBit1", "alice1"); wm1.CreateWallet("TumbleBit1", "bob1"); // Create the source and destination wallets for node 2 var wm2 = node2.FullNode.NodeService <IWalletManager>() as WalletManager; wm2.CreateWallet("TumbleBit1", "alice2"); wm2.CreateWallet("TumbleBit1", "bob2"); // Mined coins only mature after 100 blocks on regtest // Additionally, we need to force Segwit to activate in order for NTB to work correctly coreNode.FindBlock(450); var rpc1 = node1.CreateRPCClient(); var rpc2 = node2.CreateRPCClient(); rpc3.AddNode(node1.Endpoint, false); rpc3.AddNode(node2.Endpoint, false); rpc1.AddNode(coreNode.Endpoint, false); rpc1.AddNode(node2.Endpoint, false); var amount = new Money(5.0m, MoneyUnit.BTC); var destination1 = wm1.GetUnusedAddress(new WalletAccountReference("alice1", "account 0")); var destination2 = wm2.GetUnusedAddress(new WalletAccountReference("alice2", "account 0")); rpc3.SendToAddress(BitcoinAddress.Create(destination1.Address, Network.RegTest), amount); rpc3.SendToAddress(BitcoinAddress.Create(destination2.Address, Network.RegTest), amount); Console.WriteLine("Waiting for transactions to propagate and finalise"); Thread.Sleep(5000); coreNode.FindBlock(1); // Wait for SBFN to sync with the core node TestHelper.WaitLoop(() => rpc1.GetBestBlockHash() == rpc3.GetBestBlockHash()); TestHelper.WaitLoop(() => rpc2.GetBestBlockHash() == rpc3.GetBestBlockHash()); // Test implementation note: the coins do not seem to immediately appear in the wallet. // This is possibly some sort of race condition between the wallet manager and block generation/sync. // This extra delay seems to ensure that the coins are definitely in the wallet by the time the // transaction count gets logged to the console below. // Wait instead of generating a block Thread.Sleep(5000); var loggerFactory1 = node1.FullNode.NodeService <ILoggerFactory>(); var loggerFactory2 = node2.FullNode.NodeService <ILoggerFactory>(); var logger1 = loggerFactory1.CreateLogger(this.GetType().FullName); var logger2 = loggerFactory2.CreateLogger(this.GetType().FullName); logger1.LogError("(1) Number of wallet transactions: " + wm1.GetSpendableTransactionsInWallet("alice1").Count()); logger2.LogError("(2) Number of wallet transactions: " + wm2.GetSpendableTransactionsInWallet("alice2").Count()); // Connect to server and start tumbling using (client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Sample returned output // {"tumbler":"ctb://<onionaddress>.onion?h=<confighash>","denomination":"0.01000000","fee":"0.00010000","network":"RegTest","estimate":"22200"} var connectResponse = client.GetStringAsync(apiSettings1.ApiUri + "api/TumbleBit/connect").GetAwaiter().GetResult(); //Assert.StartsWith("[{\"", connectResponse); var tumbleModel = new TumbleRequest { OriginWalletName = "alice1", OriginWalletPassword = "******", DestinationWalletName = "bob1" }; var tumbleContent = new StringContent(tumbleModel.ToString(), Encoding.UTF8, "application/json"); var tumbleResponse = client.PostAsync(apiSettings1.ApiUri + "api/TumbleBit/tumble", tumbleContent).GetAwaiter().GetResult(); // Note that the TB client takes about 30 seconds to completely start up, as it has to check the server parameters and // RSA key proofs //Assert.StartsWith("[{\"", tumbleResponse); } using (client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var connectResponse = client.GetStringAsync(apiSettings2.ApiUri + "api/TumbleBit/connect").GetAwaiter().GetResult(); var tumbleModel = new TumbleRequest { OriginWalletName = "alice2", OriginWalletPassword = "******", DestinationWalletName = "bob2" }; var tumbleContent = new StringContent(tumbleModel.ToString(), Encoding.UTF8, "application/json"); var tumbleResponse = client.PostAsync(apiSettings2.ApiUri + "api/TumbleBit/tumble", tumbleContent).GetAwaiter().GetResult(); // Note that the TB client takes about 30 seconds to completely start up, as it has to check the server parameters and // RSA key proofs } logger1.LogError("(1) About to start tumbling loop"); logger2.LogError("(2) About to start tumbling loop"); // TODO: Move forward specific numbers of blocks and check interim states? TB tests already do that for (int i = 0; i < 80; i++) { rpc3.Generate(1); builder.SyncNodes(); // Try to ensure the invalid phase error does not occur // (seems to occur when the server has not yet processed a new block and the client has) TestHelper.WaitLoop(() => rpc1.GetBestBlockHash() == rpc3.GetBestBlockHash()); TestHelper.WaitLoop(() => rpc2.GetBestBlockHash() == rpc3.GetBestBlockHash()); /*var mempool = node1.FullNode.NodeService<MempoolManager>(); * var mempoolTx = mempool.GetMempoolAsync().Result; * if (mempoolTx.Count > 0) * { * Console.WriteLine("--- Mempool contents ---"); * foreach (var tx in mempoolTx) * { * var hex = mempool.GetTransaction(tx).Result; * Console.WriteLine(tx + " ->"); * Console.WriteLine(hex); * Console.WriteLine("---"); * } * }*/ Thread.Sleep(20000); } // Check destination wallet for tumbled coins // TODO: Need to amend TumblerService so that it can be shut down within the test if (client != null) { client.Dispose(); client = null; } } }
internal static ServiceRepository GetServiceProvider([CanBeNull] this LoggingConfiguration loggingConfiguration) { return(loggingConfiguration?.LogFactory?.ServiceRepository ?? LogManager.LogFactory.ServiceRepository); }
public static ILoggerManager GetLoggingService(ILoggingConfiguration loggingConfiguration) { var config = new NLog.Config.LoggingConfiguration(); LogLevel minLogLevel = LogLevel.Error; switch (loggingConfiguration.LogLevel) { case Types.Enums.LogLevel.Info: minLogLevel = LogLevel.Info; break; case Types.Enums.LogLevel.Trace: minLogLevel = LogLevel.Trace; break; case Types.Enums.LogLevel.Debug: minLogLevel = LogLevel.Debug; break; case Types.Enums.LogLevel.Warn: minLogLevel = LogLevel.Warn; break; case Types.Enums.LogLevel.Error: minLogLevel = LogLevel.Error; break; case Types.Enums.LogLevel.Fatal: minLogLevel = LogLevel.Fatal; break; } var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "log.txt", DeleteOldFileOnStartup = true, }; if (loggingConfiguration.LogVerbosity == LogVerbosity.Quit) { logfile.Layout = "Local-Date=${longdate}|Level=${level}|Log-Message=${message}|Error-Message=${event-context:item=error-message}"; } else if (loggingConfiguration.LogVerbosity == LogVerbosity.Diagnostic) { logfile.Layout = "Local-Date=${longdate}|Level=${level}|Log-Message=${message}|Error-Source=${event-context:item=error-source}|Error-Class=${event-context:item=error-class}|Error-Method=${event-context:item=error-method}|Error-Message=${event-context:item=error-message}|Inner-Error-Message=${event-context:item=inner-error-message}"; } else { logfile.Layout = "Local-Date=${longdate}|Level=${level}|Log-Message=${message}|Error-Source=${event-context:item=error-source}|Error-Class=${event-context:item=error-class}|Error-Method=${event-context:item=error-method}|Error-Message=${event-context:item=error-message}|Inner-Error-Message=${event-context:item=inner-error-message}|Stack-Trace=${event-context:item=stack-trace}"; } config.AddRule(minLogLevel, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; ConfigurationItemFactory.Default.LayoutRenderers .RegisterDefinition("utc_date", typeof(UtcDateRenderer)); if (!loggingConfiguration.IsLoggingEnabled) { LogManager.GlobalThreshold = LogLevel.Off; } ILoggerManager logger = (ILoggerManager)NLog.LogManager.GetLogger("NLogLogger", typeof(LoggerManager)); return(logger); }
private static void SetupLogWarning(NLogConfig config, FileTarget tbTarget, LogLevel logLevel) { // Catch all for any remaining warnings/errors that slip through the filters config.LoggingRules.Add(new LoggingRule("*", logLevel, tbTarget)); }
private static void SetupLogError(NLogConfig config, FileTarget tbTarget, LogLevel logLevel) { config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.RPC.*", logLevel, tbTarget)); config.LoggingRules.Add(new LoggingRule("Breeze.*", logLevel, tbTarget)); config.LoggingRules.Add(new LoggingRule("NTumbleBit.*", logLevel, tbTarget)); }
public static NLogInput ConfigureNLogInput(this DiagnosticPipeline diagnosticPipeline, LogLevel minLogLevel = null, string loggerNamePattern = "*", Config.LoggingConfiguration loggingConfig = null) { Requires.NotNull(diagnosticPipeline, nameof(diagnosticPipeline)); var input = diagnosticPipeline.Inputs.OfType <NLogInput>().FirstOrDefault(); if (input == null) { return(null); } if (minLogLevel != null) { var config = loggingConfig ?? LogManager.Configuration ?? new Config.LoggingConfiguration(); config.AddRule(minLogLevel, LogLevel.Fatal, input, loggerNamePattern); if (loggingConfig == null) { if (LogManager.Configuration == null) { LogManager.Configuration = config; } else { LogManager.ReconfigExistingLoggers(); } } } return(input); }
public static void StartLogging(string filename) { ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("InvariantCulture", typeof(InvariantCultureLayoutRendererWrapper)); var config = new NLog.Config.LoggingConfiguration(); for (int i = logsToKeep; i >= 0; i--) { var _filename = getFormattedLogFilename(filename, i - 1); if (File.Exists(_filename)) { var newName = getFormattedLogFilename(filename, i); if (string.IsNullOrEmpty(newName)) //If something went wrong generating the name, just give up { break; } try { File.Copy(_filename, newName, true); } catch (Exception e) { Console.WriteLine($"Failed to rotate log file {_filename} to {newName}\n{e}"); } } } try { File.Delete(filename); } catch (Exception e) { Console.WriteLine($"Failed to delete old log!\n{e}"); } if (minLevel == LogLevel.Trace) { CurrentLayout = traceLayout; } // var logfile = new NLog.Targets.FileTarget("logfile") { FileName = filename, Layout = layout }; var logconsole = new NLog.Targets.ColoredConsoleTarget("logconsole") { Layout = CurrentLayout }; bool isDebug = false; Debug.Assert(isDebug = true); if (Environment.GetCommandLineArgs().Contains("-TRACE") || isDebug) { config.AddRule(LogLevel.Trace, LogLevel.Fatal, logconsole); } else { config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole); } // Rules for mapping loggers to targets //config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; Common.ConsoleHelper.CreateConsole(filename); if (!Environment.GetCommandLineArgs().Any(x => string.Equals(x, "-CONSOLE", StringComparison.OrdinalIgnoreCase))) { Common.ConsoleHelper.HideConsole(); } GlobalLogger = LogManager.GetLogger("Global"); }
public virtual void Activated(LogFactory logFactory, LoggingConfiguration config) { // Nothing to do }
private bool TryLoadLoggingConfiguration(LogFactory logFactory, string configFile, out LoggingConfiguration config) { try { #if SILVERLIGHT && !WINDOWS_PHONE Uri configFileUri = new Uri(configFile, UriKind.Relative); var streamResourceInfo = Application.GetResourceStream(configFileUri); if (streamResourceInfo != null) { InternalLogger.Debug("Loading config from Resource {0}", configFileUri); using (var xmlReader = XmlReader.Create(streamResourceInfo.Stream)) { config = LoadXmlLoggingConfiguration(xmlReader, null, logFactory); return(true); } } #else if (_appEnvironment.FileExists(configFile)) { config = LoadXmlLoggingConfigurationFile(logFactory, configFile); return(true); // File exists, and maybe the config is valid, stop search } #endif } catch (IOException ex) { InternalLogger.Warn(ex, "Skipping invalid config file location: {0}", configFile); } catch (UnauthorizedAccessException ex) { InternalLogger.Warn(ex, "Skipping inaccessible config file location: {0}", configFile); } catch (SecurityException ex) { InternalLogger.Warn(ex, "Skipping inaccessible config file location: {0}", configFile); } catch (Exception ex) { InternalLogger.Error(ex, "Failed loading from config file location: {0}", configFile); if (logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions) { throw; } if (ex.MustBeRethrown()) { throw; } } config = null; return(false); // No valid file found }
internal void ReloadConfigOnTimer(object state) { if (_reloadTimer == null && _isDisposing) { return; //timer was disposed already. } LoggingConfiguration oldConfig = (LoggingConfiguration)state; InternalLogger.Info("Reloading configuration..."); lock (_logFactory._syncRoot) { LoggingConfiguration newConfig; try { if (_isDisposing) { return; //timer was disposed already. } var currentTimer = _reloadTimer; if (currentTimer != null) { _reloadTimer = null; currentTimer.WaitForDispose(TimeSpan.Zero); } if (_logFactory._config != oldConfig) { InternalLogger.Warn("NLog Config changed in between. Not reloading."); return; } newConfig = oldConfig.ReloadNewConfig(); if (newConfig == null) { return; } } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } InternalLogger.Warn(exception, "NLog configuration failed to reload"); _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(false, exception)); return; } try { TryUnwatchConfigFile(); _logFactory.Configuration = newConfig; // Triggers LogFactory to call Activated(...) that adds file-watch again _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(true)); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } InternalLogger.Warn(exception, "NLog configuration reloaded, failed to be assigned"); _watcher.Watch(oldConfig.FileNamesToWatch); _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(false, exception)); } } }
/// <summary> /// Initializes a new instance of the <see cref="LoggingConfigurationChangedEventArgs" /> class. /// </summary> /// <param name="oldConfiguration">The old configuration.</param> /// <param name="newConfiguration">The new configuration.</param> internal LoggingConfigurationChangedEventArgs(LoggingConfiguration oldConfiguration, LoggingConfiguration newConfiguration) { this.OldConfiguration = oldConfiguration; this.NewConfiguration = newConfiguration; }
private static void SetupLogFatal(NLogConfig config, FileTarget tbTarget, LogLevel logLevel) { config.LoggingRules.Add(new LoggingRule("Breeze.*", logLevel, tbTarget)); }
/// <summary> /// Initializes a new instance of the <see cref="LoggingConfigurationChangedEventArgs" /> class. /// </summary> /// <param name="activatedConfiguration">The new configuration.</param> /// <param name="deactivatedConfiguration">The old configuration.</param> public LoggingConfigurationChangedEventArgs(LoggingConfiguration activatedConfiguration, LoggingConfiguration deactivatedConfiguration) { ActivatedConfiguration = activatedConfiguration; DeactivatedConfiguration = deactivatedConfiguration; }