public AddTarget ( string name, |
||
name | string | /// Name of the target. /// |
target | /// The target object. /// | |
return | void |
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; }
private void SetupLogging() { // Step 1. Create configuration object LoggingConfiguration configuration = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration FileTarget fileTarget = new FileTarget(); configuration.AddTarget("file", fileTarget); NLogViewerTarget log_viewer_target = new NLogViewerTarget(); log_viewer_target.Name = "viewer"; log_viewer_target.Address = "udp://127.0.0.1:9999"; configuration.AddTarget("viewer", log_viewer_target); // Step 3. Set target properties fileTarget.FileName = "${basedir}/file.txt"; fileTarget.Layout = "${date} ${level} ${message}"; // Step 4. Define rules LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, fileTarget); configuration.LoggingRules.Add(rule1); LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, log_viewer_target); configuration.LoggingRules.Add(rule2); // Step 5. Activate the configuration LogManager.Configuration = configuration; // Example usage log.Debug("Application started"); }
public void InitNLog() { // Step 1. Create configuration object NLog.Config.LoggingConfiguration gConfig = new NLog.Config.LoggingConfiguration(); // Step 2. Create targets and add them to the configuration NLog.Targets.ColoredConsoleTarget consoleTarget = new NLog.Targets.ColoredConsoleTarget(); gConfig.AddTarget("console", consoleTarget); NLog.Targets.FileTarget fileTarget = new NLog.Targets.FileTarget(); gConfig.AddTarget("file", fileTarget); // Step 3. Set target properties consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; fileTarget.FileName = System.IO.Directory.GetCurrentDirectory() + "/${shortdate}/${logger}.log"; fileTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; UnityEngine.Debug.Log(fileTarget.FileName); // Step 4. Define rules NLog.Config.LoggingRule rule1 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, consoleTarget); gConfig.LoggingRules.Add(rule1); NLog.Config.LoggingRule rule2 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, fileTarget); gConfig.LoggingRules.Add(rule2); // Step 5. Activate the configuration NLog.LogManager.Configuration = gConfig; }
private static void SetupLogging() { // Step 1. Create configuration object LoggingConfiguration config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); FileTarget fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); fileTarget.FileName = "${basedir}/file.txt"; // Step 3. Set target properties consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; fileTarget.Layout = "${date:format=HH\\:MM\\:ss} ${message}"; // Step 4. Define rules LoggingRule rule = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule); rule = new LoggingRule("*", LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule); // Step 5. Activate the configuration LogManager.Configuration = config; }
public static void ConfigureNLog() { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget { Layout = "${level:uppercase=true}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}" }; config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); var fileTarget = new FileTarget { FileName = "${basedir}/nsb_log_${date:format=yyyy-MM-dd}.txt", ArchiveDateFormat = "yyyy-MM-dd", Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}", ArchiveAboveSize = 10 * 1024 *1024, ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Rolling, MaxArchiveFiles = 10, KeepFileOpen = false }; config.AddTarget("file", fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); LogManager.Configuration = config; }
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(); }
public void Initialize() { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); var logentriesTarget = new Le.LeTarget(); config.AddTarget("logentries", logentriesTarget); // Step 3. Set target properties fileTarget.FileName = "${specialfolder:folder=LocalApplicationData}/" + GlobalConstants.Paths.LogFile; fileTarget.Layout = layout; logentriesTarget.Layout = layout; // Step 4. Define rules var rule1 = new LoggingRule("*", LogLevel.Info, fileTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", LogLevel.Info, logentriesTarget); config.LoggingRules.Add(rule2); // Step 5. Activate the configuration LogManager.Configuration = config; }
// ------------------------------------------ // 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 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; }
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 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; }
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); }
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()); }
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; }
private void ConfigureLogger() { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var logsDirPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Yakuza", "Jira Assistant", "Logs"); if (Directory.Exists(logsDirPath) == false) Directory.CreateDirectory(logsDirPath); var fileTarget = new FileTarget { Name = "main", FileName = Path.Combine(logsDirPath, "Jira Assistant.log"), Layout = "${longdate} ${uppercase:${level}} ${message} ${exception:format=tostring}", ArchiveFileName = Path.Combine(logsDirPath, "Jira Assistant.{#}.log"), ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Rolling, MaxArchiveFiles = 3, ConcurrentWrites = true }; config.AddTarget("file", fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, consoleTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget)); LogManager.Configuration = config; }
public static void ConfigureViaCode(LogLevel consoleLogLevel, LogLevel fileLogLevel) { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var consoleTarget = new ConsoleTarget(); config.AddTarget("console", consoleTarget); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); // Step 3. Set target properties consoleTarget.Layout = @"${message} ${onexception:EXCEPTION\:${exception:format=tostring}}"; fileTarget.Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} [${level:uppercase=true}] ${message} ${onexception:EXCEPTION\:${exception:format=tostring}}"; fileTarget.FileName = "C:\\temp\\logs\\SpiderOpenQuant.${date:format=yyyy-MM-dd hh}.log"; fileTarget.ConcurrentWrites = false; fileTarget.KeepFileOpen = true; fileTarget.OpenFileCacheTimeout = 60; // Step 4. Define rules var rule1 = new LoggingRule("*", consoleLogLevel, consoleTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", fileLogLevel, fileTarget); config.LoggingRules.Add(rule2); // Step 5. Activate the configuration LogManager.Configuration = config; }
private static void Configure(INewRelicConfig config) { config = config ?? NewRelicConfig.Instance; LoggingConfiguration loggingConfiguration = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget { Name = "Console" }; loggingConfiguration.AddTarget("Console", consoleTarget); loggingConfiguration.LoggingRules.Add(new LoggingRule("*", ToNLogLevel(config.LogLevel), consoleTarget)); // Store the LogLevel so it can be fetched by consumers LogLevel = config.LogLevel; if (config.LogFilePath.IsValidString() && config.LogFileName.IsValidString()) { long archiveAboveSize = config.LogLimitInKiloBytes == 0 ? long.MaxValue : config.LogLimitInKiloBytes * 1024; FileTarget fileTarget = new FileTarget { KeepFileOpen = true, ConcurrentWrites = false, FileName = Path.Combine(config.LogFilePath, config.LogFileName), MaxArchiveFiles = 1, ArchiveAboveSize = archiveAboveSize, Name = "File", }; loggingConfiguration.AddTarget("File", fileTarget); loggingConfiguration.LoggingRules.Add(new LoggingRule("*", ToNLogLevel(config.LogLevel), fileTarget)); } NLogManager.Configuration = loggingConfiguration; }
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; }
public static void BuildLogger() { var consoleTarget = new ColoredConsoleTarget { Layout = "${message} ${exception:format=tostring}" }; var debuggerTarget = new DebuggerTarget() { Layout = "${message} ${exception:format=tostring}" }; var consoleRule = new LoggingRule("*", LogLevel.Debug, consoleTarget); var debuggerRule = new LoggingRule("*", LogLevel.Debug, debuggerTarget); var config = new LoggingConfiguration(); config.LoggingRules.Add(consoleRule); config.LoggingRules.Add(debuggerRule); config.AddTarget("debugger", debuggerTarget); config.AddTarget("console", consoleTarget); LogManager.Configuration = config; }
public static Logger BuildLogger() { var consoleTarget = new ColoredConsoleTarget { Layout = "${message} ${exception:format=tostring}" }; var fileName = Path.Combine(Path.GetTempPath(), "NancyOnKayak", "WebsiteLog_${shortdate}.log"); Console.WriteLine("Logging to:" + fileName); var fileTarget = new FileTarget { FileName = fileName, Layout = "${longdate} ${message} ${exception:format=tostring}", AutoFlush = true, }; var config = new LoggingConfiguration { LoggingRules = { new LoggingRule("*", LogLevel.Debug, consoleTarget), new LoggingRule("*", LogLevel.Debug, fileTarget), } }; config.AddTarget("file", fileTarget); config.AddTarget("console", consoleTarget); LogManager.Configuration = config; return LogManager.GetLogger(""); }
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 static Logger CreateLogger() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); fileTarget.FileName = "${basedir}\\AsteriskLog.txt"; fileTarget.Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss}: ${message}"; fileTarget.ArchiveFileName = "${basedir}\\archives\\log.{#####}.txt"; fileTarget.ArchiveAboveSize = 10240000; fileTarget.ArchiveNumbering = ArchiveNumberingMode.Sequence; var rule = new LoggingRule("*", LogLevel.Trace, fileTarget); config.LoggingRules.Add(rule); var errorTarget = new FileTarget(); config.AddTarget("errorfile", errorTarget); errorTarget.FileName = "${basedir}\\Errors.txt"; errorTarget.Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss}: ${message}"; errorTarget.ArchiveFileName = "${basedir}\\archives\\log.{#####}.txt"; errorTarget.ArchiveAboveSize = 10240000; errorTarget.ArchiveNumbering = ArchiveNumberingMode.Sequence; var errorsRule = new LoggingRule("*", LogLevel.Error, errorTarget); config.LoggingRules.Add(errorsRule); LogManager.Configuration = config; return LogManager.GetCurrentClassLogger(); }
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 void configureLogger() { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); consoleTarget.Layout = @"${date:format=HH\:MM\:ss} ${logger} ${message}"; fileTarget.FileName = "${basedir}/logs/${shortdate}.log"; fileTarget.EnableFileDelete = true; fileTarget.DeleteOldFileOnStartup = true; fileTarget.Layout = "${message}"; var rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget); config.LoggingRules.Add(rule2); LogManager.Configuration = config; log = LogManager.GetLogger("SeleniumTests"); }
public static void Setup() // static constructor { var config = new NLog.Config.LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}"; fileTarget.FileName = @"C:\global-logs\logs.txt"; fileTarget.Layout = "${message}"; var rule1 = new LoggingRule("*", LogLevel.Info, consoleTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule2); NLog.LogManager.Configuration = config; }
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; }
private void ConfigureLogging() { var config = new LoggingConfiguration(); config.AddTarget("debugWindow", _logWindow.Target); config.AddTarget("infoWindow", LogControl.Target); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, _logWindow.Target)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, LogControl.Target)); LogManager.Configuration = config; }
public LogBuilderTests() { var configuration = new LoggingConfiguration(); var t1 = new LastLogEventListTarget { Name = "t1" }; var t2 = new DebugTarget { Name = "t2", Layout = "${message}" }; configuration.AddTarget(t1); configuration.AddTarget(t2); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t1)); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t2)); LogManager.Configuration = configuration; }
static ThisAddIn() { NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); NLog.Targets.Target t; //System.Diagnostics.Trace.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().CodeBase); // eg file:///C:/Users/jharrop/Documents/Visual Studio 2010/Projects/com.plutext.search/com.plutext.search.main/bin/Debug/com.plutext.search.main.DLL if (System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Contains("Debug")) { t = new NLog.Targets.DebuggerTarget(); ((NLog.Targets.DebuggerTarget)t).Layout = "${callsite} ${message}"; } else { t = new NLog.Targets.FileTarget(); ((NLog.Targets.FileTarget)t).FileName = System.IO.Path.GetTempPath() + "plutext.txt"; //// Win 7: C:\Users\jharrop\AppData\Local\Temp\ //System.Diagnostics.Trace.WriteLine("TEMP: " + System.IO.Path.GetTempPath()); ((NLog.Targets.FileTarget)t).AutoFlush = true; } //ILayout layout = new NLog.Layout("${longdate} ${callsite} ${level} ${message}"); //NLog.LayoutCollection lc = new NLog.LayoutCollection(); //lc.Add(layout); ////t.GetLayouts().Add(layout); //t.PopulateLayouts(lc); config.AddTarget("ds", t); config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, t)); LogManager.Configuration = config; log = LogManager.GetLogger("OpenDoPEFriendly"); log.Info("Logging operational."); }
private static ILoggerFactory GetNLogLoggerFactory() { LoggingConfiguration loggerConfig = new NLog.Config.LoggingConfiguration(); FileTarget fileTarget = new NLog.Targets.FileTarget() { Name = "logfile", FileName = "log.txt", Layout = "${longdate}|${level:uppercase=true}|${logger}|${event-context:item=EventId}|${message}|${ndc}" }; loggerConfig.AddTarget(fileTarget); loggerConfig.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Info, fileTarget)); //NLogLoggerFactory test = new NLogLoggerFactory(new NLogLoggerProvider(new NLogProviderOptions())); NLogLoggerFactory logLoggerFactory = new NLogLoggerFactory(); NLogProviderOptions op = new NLogProviderOptions { CaptureMessageProperties = true, CaptureMessageTemplates = true, EventIdSeparator = "|", IgnoreEmptyEventId = false, IncludeScopes = true, //ParseMessageTemplates = true //ShutdownOnDispose = true }; NLogLoggerProvider p = new NLogLoggerProvider(op, loggerConfig.LogFactory); logLoggerFactory.AddProvider(p); return(logLoggerFactory); //loggerFactory.AddNLog(new NLog.LogFactory(loggerConfig)); }
private static void SetupTumbleBitNLogs(NodeSettings nodeSettings) { NLog.Config.LoggingConfiguration config = LogManager.Configuration; var folder = Path.Combine(nodeSettings.DataDir, "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); config.LoggingRules.Add(ruleTb); config.AddTarget(tbTarget); // Apply new rules. LogManager.ReconfigExistingLoggers(); }
private static void SetupTumbleBitNLogs(NodeSettings nodeSettings) { NLogConfig config = LogManager.Configuration; var folder = Path.Combine(nodeSettings.DataDir, "Logs"); var tbTarget = new FileTarget { Name = "tumblebit", FileName = Path.Combine(folder, "tumblebit.txt"), ArchiveFileName = Path.Combine(folder, "tb-${date:universalTime=true:format=yyyy-MM-dd}.txt"), ArchiveNumbering = ArchiveNumberingMode.Sequence, ArchiveEvery = FileArchivePeriod.Day, MaxArchiveFiles = 7, Layout = "[${longdate:universalTime=true} ${threadid}${mdlc:item=id}] ${level:uppercase=true}: ${callsite} ${message}", Encoding = Encoding.UTF8 }; SetupLogs(config, tbTarget); config.AddTarget(tbTarget); // Apply new rules. LogManager.ReconfigExistingLoggers(); }
public LoggingConfiguration(IProgram program, IOperatingSystem os, IVSServices vsservice) { NLog.Config.LoggingConfiguration conf; string assemblyFolder = program.ExecutingAssemblyDirectory; try { conf = new XmlLoggingConfiguration(Path.Combine(assemblyFolder, "NLog.config"), true); } catch (Exception ex) { vsservice.ActivityLogError(string.Format(CultureInfo.InvariantCulture, "Error loading nlog.config. {0}", ex)); conf = new NLog.Config.LoggingConfiguration(); } var fileTarget = conf.FindTargetByName("file") as FileTarget; if (fileTarget == null) { fileTarget = new FileTarget(); conf.AddTarget(Path.GetRandomFileName(), fileTarget); conf.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget)); } fileTarget.FileName = Path.Combine(os.Environment.GetLocalGitHubApplicationDataPath(), "extension.log"); fileTarget.Layout = layout; try { LogManager.Configuration = conf; } catch (Exception ex) { vsservice.ActivityLogError(string.Format(CultureInfo.InvariantCulture, "Error configuring the log. {0}", ex)); } }
public static NLog.Config.LoggingConfiguration GetConfiguration() { NLog.Config.ConfigurationItemFactory.Default.Targets.RegisterDefinition("AzureTableStorageTarget", typeof(NLog.Extensions.AzureTableStorage.AzureTableStorageTarget)); NLog.Config.ConfigurationItemFactory.Default.Targets.RegisterDefinition("AzureTableStorageTargetCustom", typeof(NLogAzureStorageTarget)); NLog.Config.ConfigurationItemFactory.Default.Targets.RegisterDefinition("AzureTableStorageTargetCustom", typeof(NLog.Targets.ConsoleTarget)); NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); var targetAzure = new NLog.Extensions.AzureTableStorage.AzureTableStorageTarget(); targetAzure.Layout = "${json-encode:jsonEncode=True:inner=${message}}"; targetAzure.Name = "tableStorage"; targetAzure.ConnectionString = JehovaJireh.Configuration.CloudConfiguration.GetConnectionString("LogStorageConnectionString"); targetAzure.TableName = "logging"; config.AddTarget("tableStorage", targetAzure); var targetAzureCustom = new NLogAzureStorageTarget(); //targetAzureCustom.Layout = "${json-encode:jsonEncode=True:inner=${message}}"; targetAzureCustom.Name = "tableStorageCustom"; targetAzureCustom.TableStorageConnectionStringName = "LogStorageConnectionString"; targetAzureCustom.TableName = "logging"; config.AddTarget("tableStorageCustom", targetAzure); var targetConsole = new NLog.Targets.ConsoleTarget(); targetConsole.Layout = "${json-encode:jsonEncode=True:inner=${message}}"; targetConsole.Name = "console"; config.AddTarget("console", targetConsole); var ruleNHibernate = new NLog.Config.LoggingRule("NHibernate*", NLog.LogLevel.Debug, targetAzureCustom); var ruleApplication = new NLog.Config.LoggingRule("JehovaJireh*", NLog.LogLevel.Trace, targetAzureCustom); config.LoggingRules.Add(ruleNHibernate); config.LoggingRules.Add(ruleApplication); var ruleConsole = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, targetConsole); config.LoggingRules.Add(ruleConsole); return(config); }
private static NLog.Config.LoggingConfiguration GetNLogConfig() { var config = new NLog.Config.LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}"; var rule1 = new LoggingRule("a", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule1); return(config); }
public static Logger SetupLogging(AllCommandOptions opts) { var config = new NLog.Config.LoggingConfiguration(); if (String.IsNullOrEmpty(opts.LogFilePath)) { opts.LogFilePath = Utils.GetPath(Utils.AppPath.defaultLog); //if using default app log path clean up previous for convenience in reading if (File.Exists(opts.LogFilePath)) { File.Delete(opts.LogFilePath); } } LogLevel log_level = LogLevel.Error;//default if (String.IsNullOrEmpty(opts.LogFileLevel)) { opts.LogFileLevel = "Error"; } try { log_level = LogLevel.FromString(opts.LogFileLevel); } catch (Exception) { throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-v"))); } using (var fileTarget = new FileTarget() { Name = "LogFile", FileName = opts.LogFilePath, Layout = @"${date:universalTime=true:format=s} ${threadid} ${level:uppercase=true} - ${message}", ForceMutexConcurrentWrites = true }) { config.AddTarget(fileTarget); config.LoggingRules.Add(new LoggingRule("CST.ApplicationInspector", log_level, fileTarget)); } LogFilePath = opts.LogFilePath;//preserve for console path msg LogManager.Configuration = config; Logger logger = LogManager.GetLogger("CST.ApplicationInspector"); logger.Info("[" + DateTime.Now.ToLocalTime() + "] //////////////////////////////////////////////////////////"); return(logger); }
private static void SetupTumbleBitNLogs(NodeSettings nodeSettings) { NLog.Config.LoggingConfiguration config = LogManager.Configuration; var folder = Path.Combine(nodeSettings.DataDir, "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; // Attempt to log all information that is pertinent for debugging. // In particular, suppress the watch only wallet's debug-level entries as they are highly verbose. config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.Api.*", NLog.LogLevel.Debug, tbTarget)); //config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.BlockStore.*", NLog.LogLevel.Error, tbTarget)); //config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.Consensus.*", NLog.LogLevel.Error, tbTarget)); config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.LightWallet.*", NLog.LogLevel.Debug, tbTarget)); //config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.MemoryPool.*", NLog.LogLevel.Error, tbTarget)); //config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.Notifications.*", NLog.LogLevel.Error, tbTarget)); config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.RPC.*", NLog.LogLevel.Error, tbTarget)); config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.Wallet.*", NLog.LogLevel.Debug, tbTarget)); config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Features.WatchOnlyWallet.*", NLog.LogLevel.Info, tbTarget)); config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.BlockPulling.*", NLog.LogLevel.Info, tbTarget)); // Has quite verbose Trace logs config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Connection.*", NLog.LogLevel.Info, tbTarget)); config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.FullNode", NLog.LogLevel.Info, tbTarget)); config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.P2P.*", NLog.LogLevel.Debug, tbTarget)); // Quite verbose Trace logs config.LoggingRules.Add(new LoggingRule("Stratis.Bitcoin.Utilities.*", NLog.LogLevel.Info, tbTarget)); config.LoggingRules.Add(new LoggingRule("api.request.logger", NLog.LogLevel.Trace, tbTarget)); // Shows incoming API requests. Errors should be trapped by feature logs // The log rules specific to Breeze Privacy Protocol and masternode functionality. // Note however that the NTB runtime performs its own logging internally, and it is non-trivial to override it. config.LoggingRules.Add(new LoggingRule("Breeze.TumbleBit.Client.*", NLog.LogLevel.Debug, tbTarget)); config.LoggingRules.Add(new LoggingRule("Breeze.Registration.*", NLog.LogLevel.Debug, tbTarget)); config.LoggingRules.Add(new LoggingRule("BreezeCommon.*", NLog.LogLevel.Debug, tbTarget)); // Catch all for any remaining warnings/errors that slip through the filters config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Warn, tbTarget)); config.AddTarget(tbTarget); // Apply new rules. LogManager.ReconfigExistingLoggers(); }
static void SetupLogging(string logFilePath, string logFileLevel) { var config = new NLog.Config.LoggingConfiguration(); if (String.IsNullOrEmpty(logFilePath)) { logFilePath = Utils.GetPath(Utils.AppPath.defaultLog); //if using default app log path clean up previous for convenience in reading if (File.Exists(logFilePath)) { File.Delete(logFilePath); } } LogLevel log_level = LogLevel.Error;//default try { log_level = LogLevel.FromString(logFileLevel); } catch (Exception) { throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-v"))); } using (var fileTarget = new FileTarget() { Name = "LogFile", FileName = logFilePath, Layout = @"${date:universalTime=true:format=s} ${threadid} ${level:uppercase=true} - ${message}", ForceMutexConcurrentWrites = true }) { config.AddTarget(fileTarget); config.LoggingRules.Add(new LoggingRule("*", log_level, fileTarget)); } LogManager.Configuration = config; Logger = LogManager.GetCurrentClassLogger(); Logger.Info("[" + DateTime.Now.ToLocalTime() + "] //////////////////////////////////////////////////////////"); WriteOnce.Log = Logger;//allows log to be written to as well as console or output file }
static LoggingManager() { #region Microsoft Logging Test LoggerFactory = new MicrosoftMigrationLoggerFactory( new LoggerFactory() .AddConsole(Microsoft.Extensions.Logging.LogLevel.Trace, true) .AddDebug(Microsoft.Extensions.Logging.LogLevel.Trace)); #endregion #region NLog Test DebuggerTarget debugTarget = new DebuggerTarget(); debugTarget.Layout = "[${longdate}] [${uppercase:${level}}] [${logger}] [${gdc:item=assemblyVersion}] ${newline} [${ndlc}] ${newline} ${message} ${newline} ${exception:format=tostring}"; var config = new NLog.Config.LoggingConfiguration(); config.AddTarget("1", debugTarget); LoggingRule rule1 = new LoggingRule("*", NLog.LogLevel.Debug, debugTarget); LoggingRule rule2 = new LoggingRule("*", NLog.LogLevel.Info, debugTarget); LoggingRule rule3 = new LoggingRule("*", NLog.LogLevel.Error, debugTarget); LoggingRule rule4 = new LoggingRule("*", NLog.LogLevel.Fatal, debugTarget); LoggingRule rule5 = new LoggingRule("*", NLog.LogLevel.Trace, debugTarget); LoggingRule rule6 = new LoggingRule("*", NLog.LogLevel.Warn, debugTarget); LoggingRule rule7 = new LoggingRule("*", NLog.LogLevel.Off, debugTarget); config.LoggingRules.Add(rule1); config.LoggingRules.Add(rule2); config.LoggingRules.Add(rule3); config.LoggingRules.Add(rule4); config.LoggingRules.Add(rule5); config.LoggingRules.Add(rule6); config.LoggingRules.Add(rule7); LoggerFactory = new SimpleSoft.Database.Migrator.NLogMigrationLoggerFactory( new LogFactory(config) ); #endregion }
public static void Configure(string connectionString, string logLevel, string schema) { var config = new NLog.Config.LoggingConfiguration(); var sqlServerTarget = new DatabaseTarget("sqlserver"); sqlServerTarget.ConnectionString = connectionString; sqlServerTarget.CommandText = $@"INSERT INTO [{schema}].[TaskLog] ( Level, Logger, Message, Exception ) VALUES ( @level, @logger, @message, @exception )"; sqlServerTarget.Parameters.Add(new DatabaseParameterInfo("@level", new SimpleLayout("${level}"))); sqlServerTarget.Parameters.Add(new DatabaseParameterInfo("@logger", new SimpleLayout("${logger}"))); sqlServerTarget.Parameters.Add(new DatabaseParameterInfo("@message", new SimpleLayout("${message}"))); sqlServerTarget.Parameters.Add(new DatabaseParameterInfo("@exception", new SimpleLayout("${exception:tostring}"))); config.AddTarget("sqlserver", sqlServerTarget); config.LoggingRules.Add(new LoggingRule("*", GetLogLevel(logLevel), sqlServerTarget)); LogManager.Configuration = config; LogManager.ThrowExceptions = true; }
public static void InitSamayLogger(string samayDB_ConnectionString) { //initialize the logger to log using NLog to SQLite Database try { InitConversions(); DatabaseParameterInfo param; dbTarget.KeepConnection = false; dbTarget.UseTransactions = false; dbTarget.DBProvider = "System.Data.SQLite.SQLiteConnection, System.Data.SQLite"; dbTarget.ConnectionString = samayDB_ConnectionString; dbTarget.CommandText = "INSERT into LOGS (TimeStamp, Level, Message, JobName, TaskName) values(@Timestamp, @Loglevel,@Message, @JobName, @TaskName)"; param = new DatabaseParameterInfo(); param.Name = "@Timestamp"; //param.Layout = "${longdate}"; // param.Layout = new NLog.LayoutRenderers.DateLayoutRenderer();// param.Layout = "${event-context:item=timestamp}"; dbTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@Loglevel"; param.Layout = "${level}"; dbTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@Message"; param.Layout = "${message}"; dbTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@JobName"; param.Layout = "${event-context:item=jobname}"; dbTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@TaskName"; param.Layout = "${event-context:item=taskname}"; dbTarget.Parameters.Add(param); #if DEBUG config.AddTarget("Console", consoleTarget); consoleTarget.Layout = "${date:format=HH\\:mm\\:ss} ${logger} ${message}"; #endif fileTarget.Layout = "${longdate} ${logger} ${message}"; fileTarget.FileName = @"c:\samay\logs\logfile.txt"; //fileTarget.ArchiveFileName = @"c:\samay\archives\log.{#}.txt"; //fileTarget.ArchiveEvery = FileArchivePeriod.Day; //fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date; //fileTarget.MaxArchiveFiles = 7; //fileTarget.ConcurrentWrites = true; //fileTarget.KeepFileOpen = false; config.AddTarget("file", fileTarget); fileTarget.Layout = "${longdate} ${logger} ${message}"; fileTarget.FileName = "${basedir}/log.txt"; fileTarget.ArchiveFileName = "${basedir}/archives/log.{#}.txt"; fileTarget.ArchiveEvery = FileArchivePeriod.Day; fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date; fileTarget.MaxArchiveFiles = 7; fileTarget.ConcurrentWrites = true; fileTarget.KeepFileOpen = false; config.AddTarget("file", fileTarget); config.AddTarget("dbTarget", dbTarget); config.AddTarget("file", fileTarget); config.AddTarget("dbTarget", dbTarget); } catch { } finally { LogManager.Configuration = config; } }
/// <summary> /// Setup application inspector logging; 1 file per process /// </summary> /// <param name="opts"></param> /// <returns></returns> public static Logger SetupLogging(CommandOptions opts, bool onErrorConsole = false) { //prevent being called again if already set unless closed first if (Logger != null) { return(Logger); } var config = new NLog.Config.LoggingConfiguration(); if (String.IsNullOrEmpty(opts.LogFilePath)) { opts.LogFilePath = Utils.GetPath(Utils.AppPath.defaultLog); } //clean up previous for convenience in reading if (File.Exists(opts.LogFilePath)) { // Read the file and display it line by line. System.IO.StreamReader file = new System.IO.StreamReader(opts.LogFilePath); String line = file.ReadLine(); file.Close(); if (!String.IsNullOrEmpty(line)) { if (line.Contains("AppInsLog"))//prevent file other than our logs from deletion { File.Delete(opts.LogFilePath); } else { if (Utils.CLIExecutionContext && onErrorConsole) { WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_LOG_PATH, opts.LogFilePath), true, WriteOnce.ConsoleVerbosity.Low, false); } throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_LOG_PATH, opts.LogFilePath)); } } } else { try { File.WriteAllText(opts.LogFilePath, "");//verify log file path is writable } catch (Exception e) { WriteOnce.SafeLog(e.Message + "\n" + e.StackTrace, NLog.LogLevel.Error); if (Utils.CLIExecutionContext && onErrorConsole) { WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, opts.LogFilePath), true, WriteOnce.ConsoleVerbosity.Low, false); } throw new OpException((MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, opts.LogFilePath))); } } LogLevel log_level = LogLevel.Error;//default if (String.IsNullOrEmpty(opts.LogFileLevel)) { opts.LogFileLevel = "Error"; } try { log_level = LogLevel.FromString(opts.LogFileLevel); } catch (Exception) { if (Utils.CLIExecutionContext && onErrorConsole) { WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-v"), true, WriteOnce.ConsoleVerbosity.Low, false); } throw new OpException((MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-v"))); } using (var fileTarget = new FileTarget() { Name = "LogFile", FileName = opts.LogFilePath, Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} ${threadid} ${level:uppercase=true} - AppInsLog - ${message}", ForceMutexConcurrentWrites = true }) { config.AddTarget(fileTarget); config.LoggingRules.Add(new LoggingRule("CST.ApplicationInspector", log_level, fileTarget)); } LogFilePath = opts.LogFilePath;//preserve for console path msg LogManager.Configuration = config; Logger = LogManager.GetLogger("CST.ApplicationInspector"); return(Logger); }
private void PluginSturtup() //try to rename -> enum should still work { //setup NLog // Step 1. Create configuration object var config = new NLog.Config.LoggingConfiguration(); // Step 2. Create targets var debugTarget = new DebugTarget("target1") { Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" }; config.AddTarget(debugTarget); var fileTarget = new FileTarget("target2") { FileName = "D:/logs/Plugin/${shortdate}.log", Layout = "${longdate} ${uppercase:${level}} ${message} ${exception}" }; config.AddTarget(fileTarget); // Step 3. Define rules var rule1 = new LoggingRule("*", LogLevel.Debug, debugTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget); config.LoggingRules.Add(rule2); // Step 4. Activate the configuration LogManager.Configuration = config; try { _mbTcpHelper = new MusicBeeTcpServer(); } catch (Exception e) { Logger.Fatal(e, "Failed to establish connection, closing plugin"); Close(PluginCloseReason.StopNoUnload); } _mbTcpHelper.RequestArrived += ProcessRequest; SendPlayerInitializedArgs(); _commandDictionary = new Dictionary <int, Delegate>() { { 1, _mbApiInterface.MB_ReleaseString }, { 2, _mbApiInterface.MB_Trace }, { 3, _mbApiInterface.Setting_GetPersistentStoragePath }, { 4, _mbApiInterface.Setting_GetSkin }, { 5, _mbApiInterface.Setting_GetSkinElementColour }, { 6, _mbApiInterface.Setting_IsWindowBordersSkinned }, { 7, _mbApiInterface.Library_GetFileProperty }, { 8, _mbApiInterface.Library_GetFileTag }, { 9, _mbApiInterface.Library_SetFileTag }, { 10, _mbApiInterface.Library_CommitTagsToFile }, { 11, _mbApiInterface.Library_GetLyrics }, { 12, _mbApiInterface.Library_GetArtwork }, { 13, _mbApiInterface.Library_QueryFiles }, { 14, _mbApiInterface.Library_QueryGetNextFile }, { 15, _mbApiInterface.Player_GetPosition }, { 16, _mbApiInterface.Player_SetPosition }, { 17, _mbApiInterface.Player_GetPlayState }, { 18, _mbApiInterface.Player_PlayPause }, { 19, _mbApiInterface.Player_Stop }, { 20, _mbApiInterface.Player_StopAfterCurrent }, { 21, _mbApiInterface.Player_PlayPreviousTrack }, { 22, _mbApiInterface.Player_PlayNextTrack }, { 23, _mbApiInterface.Player_StartAutoDj }, { 24, _mbApiInterface.Player_EndAutoDj }, { 25, _mbApiInterface.Player_GetVolume }, { 26, _mbApiInterface.Player_SetVolume }, { 27, _mbApiInterface.Player_GetMute }, { 28, _mbApiInterface.Player_SetMute }, { 29, _mbApiInterface.Player_GetShuffle }, { 30, _mbApiInterface.Player_SetShuffle }, { 31, _mbApiInterface.Player_GetRepeat }, { 32, _mbApiInterface.Player_SetRepeat }, { 33, _mbApiInterface.Player_GetEqualiserEnabled }, { 34, _mbApiInterface.Player_SetEqualiserEnabled }, { 35, _mbApiInterface.Player_GetDspEnabled }, { 36, _mbApiInterface.Player_SetDspEnabled }, { 37, _mbApiInterface.Player_GetScrobbleEnabled }, { 38, _mbApiInterface.Player_SetScrobbleEnabled }, { 39, _mbApiInterface.NowPlaying_GetFileUrl }, { 40, _mbApiInterface.NowPlaying_GetDuration }, { 41, _mbApiInterface.NowPlaying_GetFileProperty }, { 42, _mbApiInterface.NowPlaying_GetFileTag }, { 43, _mbApiInterface.NowPlaying_GetLyrics }, { 44, _mbApiInterface.NowPlaying_GetArtwork }, { 45, _mbApiInterface.NowPlayingList_Clear }, { 46, _mbApiInterface.NowPlayingList_QueryFiles }, { 47, _mbApiInterface.NowPlayingList_QueryGetNextFile }, { 48, _mbApiInterface.NowPlayingList_PlayNow }, { 49, _mbApiInterface.NowPlayingList_QueueNext }, { 50, _mbApiInterface.NowPlayingList_QueueLast }, { 51, _mbApiInterface.NowPlayingList_PlayLibraryShuffled }, { 52, _mbApiInterface.Playlist_QueryPlaylists }, { 53, _mbApiInterface.Playlist_QueryGetNextPlaylist }, { 54, _mbApiInterface.Playlist_GetType }, { 55, _mbApiInterface.Playlist_QueryFiles }, { 56, _mbApiInterface.Playlist_QueryGetNextFile }, { 57, _mbApiInterface.MB_GetWindowHandle }, { 58, _mbApiInterface.MB_RefreshPanels }, { 59, _mbApiInterface.MB_SendNotification }, { 60, _mbApiInterface.MB_AddMenuItem }, { 61, _mbApiInterface.Setting_GetFieldName }, { 62, _mbApiInterface.MB_CreateBackgroundTask }, { 63, _mbApiInterface.MB_SetBackgroundTaskMessage }, { 64, _mbApiInterface.MB_RegisterCommand }, { 65, _mbApiInterface.Setting_GetDefaultFont }, { 66, _mbApiInterface.Player_GetShowTimeRemaining }, { 67, _mbApiInterface.NowPlayingList_GetCurrentIndex }, { 68, _mbApiInterface.NowPlayingList_GetListFileUrl }, { 69, _mbApiInterface.NowPlayingList_GetFileProperty }, { 70, _mbApiInterface.NowPlayingList_GetFileTag }, { 71, _mbApiInterface.NowPlaying_GetSpectrumData }, { 72, _mbApiInterface.NowPlaying_GetSoundGraph }, { 73, _mbApiInterface.MB_GetPanelBounds }, { 74, _mbApiInterface.MB_AddPanel }, { 75, _mbApiInterface.MB_RemovePanel }, { 76, _mbApiInterface.MB_GetLocalisation }, { 77, _mbApiInterface.NowPlayingList_IsAnyPriorTracks }, { 78, _mbApiInterface.NowPlayingList_IsAnyFollowingTracks }, { 79, _mbApiInterface.Player_ShowEqualiser }, { 80, _mbApiInterface.Player_GetAutoDjEnabled }, { 81, _mbApiInterface.Player_GetStopAfterCurrentEnabled }, { 82, _mbApiInterface.Player_GetCrossfade }, { 83, _mbApiInterface.Player_SetCrossfade }, { 84, _mbApiInterface.Player_GetReplayGainMode }, { 85, _mbApiInterface.Player_SetReplayGainMode }, { 86, _mbApiInterface.Player_QueueRandomTracks }, { 87, _mbApiInterface.Setting_GetDataType }, { 88, _mbApiInterface.NowPlayingList_GetNextIndex }, { 89, _mbApiInterface.NowPlaying_GetArtistPicture }, { 90, _mbApiInterface.NowPlaying_GetDownloadedArtwork }, { 91, _mbApiInterface.MB_ShowNowPlayingAssistant }, { 92, _mbApiInterface.NowPlaying_GetDownloadedLyrics }, { 93, _mbApiInterface.Player_GetShowRatingTrack }, { 94, _mbApiInterface.Player_GetShowRatingLove }, { 95, _mbApiInterface.MB_CreateParameterisedBackgroundTask }, { 96, _mbApiInterface.Setting_GetLastFmUserId }, { 97, _mbApiInterface.Playlist_GetName }, { 98, _mbApiInterface.Playlist_CreatePlaylist }, { 99, _mbApiInterface.Playlist_SetFiles }, { 100, _mbApiInterface.Library_QuerySimilarArtists }, { 101, _mbApiInterface.Library_QueryLookupTable }, { 102, _mbApiInterface.Library_QueryGetLookupTableValue }, { 103, _mbApiInterface.NowPlayingList_QueueFilesNext }, { 104, _mbApiInterface.NowPlayingList_QueueFilesLast }, { 105, _mbApiInterface.Setting_GetWebProxy }, { 106, _mbApiInterface.NowPlayingList_RemoveAt }, { 107, _mbApiInterface.Playlist_RemoveAt }, { 108, _mbApiInterface.MB_SetPanelScrollableArea }, { 109, _mbApiInterface.MB_InvokeCommand }, { 110, _mbApiInterface.MB_OpenFilterInTab }, { 111, _mbApiInterface.MB_SetWindowSize }, { 112, _mbApiInterface.Library_GetArtistPicture }, { 113, _mbApiInterface.Pending_GetFileUrl }, { 114, _mbApiInterface.Pending_GetFileProperty }, { 115, _mbApiInterface.Pending_GetFileTag }, { 116, _mbApiInterface.Player_GetButtonEnabled }, { 117, _mbApiInterface.NowPlayingList_MoveFiles }, { 118, _mbApiInterface.Library_GetArtworkUrl }, { 119, _mbApiInterface.Library_GetArtistPictureThumb }, { 120, _mbApiInterface.NowPlaying_GetArtworkUrl }, { 121, _mbApiInterface.NowPlaying_GetDownloadedArtworkUrl }, { 122, _mbApiInterface.NowPlaying_GetArtistPictureThumb }, { 123, _mbApiInterface.Playlist_IsInList }, { 124, _mbApiInterface.Library_GetArtistPictureUrls }, { 125, _mbApiInterface.NowPlaying_GetArtistPictureUrls }, { 126, _mbApiInterface.Playlist_AppendFiles }, { 127, _mbApiInterface.Sync_FileStart }, { 128, _mbApiInterface.Sync_FileEnd }, { 129, _mbApiInterface.Library_QueryFilesEx }, { 130, _mbApiInterface.NowPlayingList_QueryFilesEx }, { 131, _mbApiInterface.Playlist_QueryFilesEx }, { 132, _mbApiInterface.Playlist_MoveFiles }, { 133, _mbApiInterface.Playlist_PlayNow }, { 134, _mbApiInterface.NowPlaying_IsSoundtrack }, { 135, _mbApiInterface.NowPlaying_GetSoundtrackPictureUrls }, { 136, _mbApiInterface.Library_GetDevicePersistentId }, { 137, _mbApiInterface.Library_SetDevicePersistentId }, { 138, _mbApiInterface.Library_FindDevicePersistentId }, { 139, _mbApiInterface.Setting_GetValue }, { 140, _mbApiInterface.Library_AddFileToLibrary }, { 141, _mbApiInterface.Playlist_DeletePlaylist }, { 142, _mbApiInterface.Library_GetSyncDelta }, { 143, _mbApiInterface.Library_GetFileTags }, { 144, _mbApiInterface.NowPlaying_GetFileTags }, { 145, _mbApiInterface.NowPlayingList_GetFileTags }, { 146, _mbApiInterface.MB_AddTreeNode }, { 147, _mbApiInterface.MB_DownloadFile }, { 148, _mbApiInterface.Setting_GetFileConvertCommandLine }, { 149, _mbApiInterface.Player_OpenStreamHandle }, { 150, _mbApiInterface.Player_UpdatePlayStatistics }, { 151, _mbApiInterface.Library_GetArtworkEx }, { 152, _mbApiInterface.Library_SetArtworkEx }, { 153, _mbApiInterface.MB_GetVisualiserInformation }, { 154, _mbApiInterface.MB_ShowVisualiser }, { 155, _mbApiInterface.MB_GetPluginViewInformation }, { 156, _mbApiInterface.MB_ShowPluginView }, { 157, _mbApiInterface.Player_GetOutputDevices }, { 158, _mbApiInterface.Player_SetOutputDevice }, { 159, _mbApiInterface.MB_UninstallPlugin } }; }
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(10000); } // 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; } } }