/// <summary> /// Adds a target for Sentry to the NLog configuration. /// </summary> /// <param name="configuration">The NLog configuration.</param> /// <param name="dsn"> The sentry DSN.</param> /// <param name="targetName"> The name to give the new target.</param> /// <param name="optionsConfig">An optional action for configuring the Sentry target options.</param> /// <returns>The configuration.</returns> public static LoggingConfiguration AddSentry(this LoggingConfiguration configuration, string dsn, string targetName, Action <SentryNLogOptions> optionsConfig = null) { var options = new SentryNLogOptions(); optionsConfig?.Invoke(options); Target.Register <SentryTarget>("Sentry"); var target = new SentryTarget(options) { Name = targetName, Layout = "${message}", }; if (dsn != null && options.Dsn == null) { options.Dsn = new Dsn(dsn); } configuration?.AddTarget(targetName, target); configuration?.AddRuleForAllLevels(targetName); return(configuration); }
static Tuple<Logger, TestTarget> CreateTarget() { var testTarget = new TestTarget(); var config = new LoggingConfiguration(); config.AddTarget(LogLevel.Trace, LogLevel.Fatal, testTarget); return Tuple.Create(new Logger("Foobar", config), testTarget); }
public virtual LoggingConfiguration CreateDefaultSettings() { // default logging config... var configuration = new LoggingConfiguration(); configuration.AddTarget(LogLevel.Trace, LogLevel.Fatal, new EtwTarget()); return configuration; }
Tuple<ILogManager, TestTarget> CreateWithLevel(LogLevel min, LogLevel max) { var testTarget = new TestTarget(); var config = new LoggingConfiguration(); config.AddTarget(min, max, testTarget); return Tuple.Create<ILogManager, TestTarget>(new LogManager(config), testTarget); }
public async Task TestBrokenTarget() { var testTarget = new TestTarget(); var config = new LoggingConfiguration(); config.AddTarget(LogLevel.Trace, LogLevel.Fatal, new BrokenTarget()); config.AddTarget(LogLevel.Trace, LogLevel.Fatal, testTarget); var target = new LogManagerBase(config); // this should ignore errors in the broken target and flip down to the working target... var logger = (Logger)target.GetLogger("Foobar"); await logger.TraceAsync("Hello, world."); // check... Assert.Equal(1, testTarget.NumWritten); Assert.Equal(LogLevel.Trace, testTarget.LastWritten.Level); Assert.Null(testTarget.LastWritten.Exception); }
static Logger() { MaxLevel = LogLevel.Trace; _logManager = new Lazy<IWinRTLogManager>(() => { var max = (PclLogLevel)MaxLevel; // Log everything for now var configuration = new LoggingConfiguration(); configuration.AddTarget(max, PclLogLevel.Fatal, new DebugTarget()); configuration.AddTarget(max, PclLogLevel.Fatal, new EtwTarget()); configuration.AddTarget(max, PclLogLevel.Fatal, new EventTarget(OnLogMessageInternal)); configuration.AddTarget(max, PclLogLevel.Fatal, new StreamingFileTarget()); LogManagerFactory.DefaultConfiguration = configuration; return (IWinRTLogManager)LogManagerFactory.DefaultLogManager; }); }
private static void Main(string[] args) { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); LogManager.Configuration = config; Foo.Bar(); Console.ReadLine(); }
private static Tuple<ILoggerAsync, TestTarget> CreateTarget() { var testTarget = new TestTarget(); var config = new LoggingConfiguration(); config.AddTarget(LogLevel.Trace, LogLevel.Fatal, testTarget); var type = Type.GetType("MetroLog.Internal.Logger, MetroLog"); var ctor = type.GetConstructors().First(); var created = ctor.Invoke(new object[]{"Foobar", config}); return Tuple.Create((ILoggerAsync)created, testTarget); }
public void SetUp() { var cfg = new LoggingConfiguration(); _logTarget = new MemoryTarget("mem") { Layout = new SimpleLayout("${Logger}|${Level}|${Message}|${exception}|${all-event-properties}") }; cfg.AddTarget(_logTarget); cfg.AddRule(global::NLog.LogLevel.Trace, global::NLog.LogLevel.Error, _logTarget); LogManager.Configuration = cfg; }
public NLogFiltering() { #region NLogFiltering LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget target = new ColoredConsoleTarget(); config.AddTarget("console", target); config.LoggingRules.Add(new LoggingRule("MyNamespace.*", LogLevel.Debug, target)); LogManager.Configuration = config; SetLoggingLibrary.NLog(); #endregion }
public async Task FileStreamingThreadSafe() { var loggingConfiguration = new LoggingConfiguration(); loggingConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal, new StreamingFileTarget()); LogManagerFactory.DefaultConfiguration = loggingConfiguration; var log = (ILoggerAsync)LogManagerFactory.DefaultLogManager.GetLogger<FileStreamingTargetTests>(); var tasks = new List<Task>(100); for (int i = 0; i < 100; i++) { var t = log.TraceAsync("What thread am I?"); tasks.Add(t); } await Task.WhenAll(tasks); }
public NLogFiltering() { #region NLogFiltering LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget target = new ColoredConsoleTarget(); config.AddTarget("console", target); config.LoggingRules.Add(new LoggingRule("MyNamespace.*", LogLevel.Debug, target)); LogManager.Configuration = config; NServiceBus.Logging.LogManager.Use<NLogFactory>(); #endregion }
Usage() { #region NLogInCode LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget { Layout = "${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}" }; config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); LogManager.Configuration = config; NServiceBus.Logging.LogManager.Use<NLogFactory>(); #endregion }
public void CustomFilter() { var filter = new ConditionBasedFilter(); filter.Condition = "starts-with('${message}','badCategory')"; filter.Action = FilterResult.Ignore; FakeAWSTarget fakeawsTarget = new FakeAWSTarget(); var config = new LoggingConfiguration(); config.AddTarget("FakeAWSTarget", fakeawsTarget); var rule = new LoggingRule("CustomFilter", LogLevel.Warn, LogLevel.Fatal, fakeawsTarget); rule.Filters.Add(filter); config.LoggingRules.Add(rule); LogManager.Configuration = config; var logger = LogManager.GetLogger("CustomFilter"); logger.Trace("goodCategory|trace"); logger.Fatal("goodCategory|fatal"); Assert.Equal(1, fakeawsTarget._core.ReceivedMessages.Count); Assert.True(fakeawsTarget._core.ReceivedMessages.ElementAt(0).Contains("fatal")); string val; while (!fakeawsTarget._core.ReceivedMessages.IsEmpty) { fakeawsTarget._core.ReceivedMessages.TryDequeue(out val); } logger.Trace("badCategory|trace"); logger.Warn("badCategory|warning"); Assert.Equal(0, fakeawsTarget._core.ReceivedMessages.Count); }
private static ILogger InitLogger() { var consoleTarget = new ConsoleTarget { Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}" }; var fileTarget = new FileTarget { Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}", FileName = Path.Combine(Environment.CurrentDirectory, "Log", "Log.txt"), }; var config = new LoggingConfiguration(); //config.AddTarget("console", consoleTarget); config.AddTarget("file", fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); LogManager.Configuration = config; return(LogManager.GetLogger("VkApi")); }
private static void SetupLogging() { // Step 1. Create configuration object LoggingConfiguration configuration = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration NLogViewerTarget log_viewer_target = new NLogViewerTarget(); configuration.AddTarget("viewer", log_viewer_target); // Step 3. Set target properties log_viewer_target.Name = "viewer"; log_viewer_target.Address = "udp://127.0.0.1:9999"; // Step 4. Define rules LoggingRule log_viewer_rule = new LoggingRule("*", LogLevel.Trace, log_viewer_target); configuration.LoggingRules.Add(log_viewer_rule); // Step 5. Activate the configuration LogManager.Configuration = configuration; }
/// <summary> /// <inheritdoc/> /// </summary> public void CreateConfiguration() { LoggingConfiguration = new LoggingConfiguration(); Target = new FileTarget { Name = "Log", FileName = SoftwareSettings.Settings.GetSettings.GetSystemPathLog + "\\${shortdate}-" + Environment.UserName + ".log", Layout = "${longdate} | ${level:uppercsae=true} : ${message} ${exception}", Header = "User name: " + Environment.UserName + Environment.NewLine + "Startup Path: " + Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName) + Environment.NewLine + "OS Version: " + Environment.OSVersion + " ${when:when='${environment:PROCESSOR_ARCHITECTURE}'='X86':inner=32:else=64} bit system on " + Environment.MachineName + Environment.NewLine + "CLR: " + Environment.Version + Environment.NewLine + "Start timestamp ${longdate}" + Environment.NewLine, Footer = "\nStop timestamp ${longdate}", Encoding = Encoding.UTF8, LineEnding = LineEndingMode.CRLF, FileAttributes = Win32FileAttributes.Hidden, DeleteOldFileOnStartup = true, MaxArchiveFiles = 10, ArchiveEvery = FileArchivePeriod.Day, ArchiveFileName = SoftwareSettings.Settings.GetSettings.GetSystemPathLog + "\\archive\\${longdate}.log", ArchiveNumbering = ArchiveNumberingMode.Rolling, ConcurrentWrites = true, AutoFlush = true }; LoggingConfiguration.AddTarget(Target); UpdateConfigurationLogLevel(); LogManager.Configuration = LoggingConfiguration; Logger = LogManager.GetCurrentClassLogger(); }
private void InitializeLogger() { var conf = new LoggingConfiguration(); // ファイル出力定義 var file = new FileTarget("logfile") { Encoding = System.Text.Encoding.UTF8, Layout = "${longdate} [${threadid:padding=2}] [${uppercase:${level:padding=-5}}] ${callsite}() - ${message}${exception:format=ToString}", FileName = "${basedir}/logs/TimeRecorder_${date:format=yyyyMMdd}.log", ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveFileName = "${basedir}/logs/TimeRecorder.log.{#}", ArchiveEvery = FileArchivePeriod.None, MaxArchiveFiles = 10 }; conf.AddTarget(file); conf.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, file)); // 設定を反映する LogManager.Configuration = conf; }
private static void InitLogger() { // 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); // Step 3. Set target properties fileTarget.FileName = "${specialfolder:folder=CommonApplicationData}/xWare/v8file.net/v8file.net_${shortdate}.log"; fileTarget.CreateDirs = true; // Step 4. Define rules var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule2); // Step 5. Activate the configuration LogManager.Configuration = config; }
/// <summary>API Entry Point</summary> public static void Main(string[] args) { var config = new LoggingConfiguration(); // targets var fileTarget = new FileTarget("fileTarget") { FileName = @"D:\Users\Dave\Documents\Visual Studio 2019\Projects\DbWebAPI\logs\DbWebAPIlog-${shortdate}.log", Layout = "${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" }; config.AddTarget(fileTarget); // rules config.AddRuleForOneLevel(NLog.LogLevel.Warn, fileTarget); config.AddRuleForOneLevel(NLog.LogLevel.Error, fileTarget); config.AddRuleForOneLevel(NLog.LogLevel.Fatal, fileTarget); LogManager.Configuration = config; //MessageHandler.DebugLog("Starting", true); CreateHostBuilder(args).Build().Run(); }
public static void Init() { Config = new LoggingConfiguration(); ConsoleTarget = new ColoredConsoleTarget(); ConsoleTarget.Layout = "${date:format=HH\\:mm\\:ss} | ${pad:padding=-6:inner=${level:uppercase=true}}| ${message}"; Config.AddTarget("console", new AsyncTargetWrapper(ConsoleTarget)); ConsoleRule = new LoggingRule("*", LogLevel.Trace, ConsoleTarget); Config.LoggingRules.Add(ConsoleRule); LogManager.Configuration = Config; LogManager.ReconfigExistingLoggers(); //foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(x => !x.GlobalAssemblyCache)) //{ // Add(assembly); //} //AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoad; }
public static Logger GetLogger() { Logger logger; LoggingConfiguration loggingConfig = new LoggingConfiguration(); // File Target var fileTarget = new FileTarget("fileTarget") { Layout = "${longdate} ${uppercase:${level}} ${message}", FileName = "${basedir}/logs/${shortdate}.log" }; // File Rule loggingConfig.AddTarget(fileTarget); loggingConfig.AddRule(LogLevel.Debug, LogLevel.Info, fileTarget, "*"); // Console Target var consoleTarget = new ColoredConsoleTarget("consoleTarget") { Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" }; // Console Rule //loggingConfig.AddTarget(consoleTarget); //loggingConfig.AddRuleForAllLevels(consoleTarget); NLog.LogManager.Configuration = loggingConfig; NLog.LogManager.ThrowConfigExceptions = true; NLog.LogManager.ThrowExceptions = true; InternalLogger.LogToConsole = true; InternalLogger.LogFile = "logs/internal.log"; InternalLogger.LogLevel = LogLevel.Debug; logger = NLog.LogManager.GetLogger("myLogger"); return(logger); }
/// <summary> /// Set up NLog logging: targets, rules... /// </summary> private void SetupFileLogging(string logLevelName = "Debug") { LogLevel logLevel; switch (logLevelName) { case "Warn": logLevel = LogLevel.Warn; break; case "Info": logLevel = LogLevel.Info; break; case "Trace": logLevel = LogLevel.Trace; break; default: logLevel = LogLevel.Debug; break; } var logConfig = new LoggingConfiguration(); var fileTarget = new FileTarget { Name = "file", FileName = $"var/{Environment.MachineName}.{ServiceName}.log", ArchiveAboveSize = 1 * Conv.MegaBytes, ArchiveFileName = $"var/{Environment.MachineName}.{ServiceName}" + ".{#}.log", MaxArchiveFiles = 9, KeepFileOpen = true, Layout = LogFormatDefault, }; logConfig.AddTarget("file", fileTarget); var logRuleFile = new LoggingRule("*", logLevel, fileTarget); logConfig.LoggingRules.Add(logRuleFile); LogManager.Configuration = logConfig; }
public void OneOff() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); // var sysLog = @"C:\temp\Archive-ForwardedEvents-test.evtx"; var sysLog = @"D:\OneDrive\Desktop\Security.evtx"; // var total = 0; using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } l.Info($"early : {es.EarliestTimestamp}"); l.Info($"last: {es.LatestTimestamp}"); } }
private void ConfigureLogging() { string loggingPath = Path.Combine(Paths.GetBaseDirectory(), $"{Assembly.GetExecutingAssembly().GetName().Name}.log"); string archivePath = Path.Combine(Paths.GetBaseDirectory(), "archives", $"{Assembly.GetExecutingAssembly().GetName().Name}.log"); var config = new LoggingConfiguration(); var logfile = new FileTarget("logfile") { FileName = loggingPath, Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:format=tostring}", ArchiveFileName = archivePath, ArchiveAboveSize = 100000000, ArchiveNumbering = ArchiveNumberingMode.DateAndSequence }; config.AddTarget(logfile); config.AddRule(GetLogLevel(), LogLevel.Fatal, logfile); LogManager.Configuration = config; DispatcherUnhandledException += (sender, e) => { _logger.Error(e.Exception, "Unhandled exception"); }; }
public static LoggingConfiguration Create(string connectionString, TraceLogLevel traceLogLevel) { var config = new LoggingConfiguration(); var databaseTarget = new DatabaseTarget(); config.AddTarget("database", databaseTarget); databaseTarget.ConnectionString = connectionString; databaseTarget.CommandText = @" INSERT INTO [dbo].[TraceLogs] ( [Logger], [Level], [ThreadId], [MachineName], [Message] ) VALUES ( @Logger, @Level, @ThreadId, @MachineName, @Message ); "; databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Logger", new SimpleLayout("${logger}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Level", new SimpleLayout("${uppercase:${level}}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@ThreadId", new SimpleLayout("${threadid}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@MachineName", new SimpleLayout("${machinename}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@CallSite", new SimpleLayout("${callsite}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@UserName", new SimpleLayout("${identity}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", new SimpleLayout("${message}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@StackTrace", new SimpleLayout("${exception:format=tostring}"))); var loggingRule = new LoggingRule("*", traceLogLevel.ToNLogLevel(), databaseTarget); config.LoggingRules.Add(loggingRule); return(config); }
// Main window loaded handler private void WindowLoaded(object sender, RoutedEventArgs e) { // Setup NLog var config = new LoggingConfiguration(); var fileTarget = new FileTarget("filetarget") { FileName = "${basedir}/Roulette.log", Layout = "[${level}] [${longdate}] ${message}" }; config.AddTarget(fileTarget); config.AddRuleForAllLevels("filetarget"); LogManager.Configuration = config; // Create controllers this.spinnerController = new SpinnerController(this.SpinnerImage); this.playersController = new PlayerController(this.spinnerController); // Add players to players list and show them in list PlayersList.ItemsSource = this.playersController.PlayersList; this.SetNewPlayersCount(null, null); }
public DataLakeStoreFileSystemClient(IAzureContext context, DataLakeStoreFileSystemCmdletBase cmdlet) : this(context) { _adlsLoggerConfig = new LoggingConfiguration(); // Custom target that logs the debug messages from the SDK to the powershell framework's debug message queue var adlsTarget = new AdlsLoggerTarget { DebugMessageQueue = cmdlet.DebugMessages }; // Add the target to the configuration _adlsLoggerConfig.AddTarget("logger", adlsTarget); //Logs all patterns of debug messages var rule = new LoggingRule("adls.dotnet.*", NLog.LogLevel.Debug, adlsTarget); _adlsLoggerConfig.LoggingRules.Add(rule); var powershellLoggingRule = new LoggingRule("adls.powershell.WebTransport", NLog.LogLevel.Debug, adlsTarget); _adlsLoggerConfig.LoggingRules.Add(powershellLoggingRule); // Enable the NLog configuration to use this LogManager.Configuration = _adlsLoggerConfig; }
/// <summary> /// Initializes the NLog logging configuration. /// </summary> /// <remarks> /// Using DLL injection, we can't place an Nlog.config file in our target directory, so we have to create the configuration during runtime. /// </remarks> public static void Initialize() { var config = new LoggingConfiguration(); var target = new FileTarget { FileName = "C:/Sc2Ai/Logs/Sc2AiBot.log", Layout = "${longdate} ${level} ${callsite} ${message}", DeleteOldFileOnStartup = true }; var targetWrapper = new AsyncTargetWrapper(target, Int32.MaxValue, AsyncTargetWrapperOverflowAction.Discard); config.AddTarget("File", targetWrapper); var rule = new LoggingRule("*", LogLevel.Trace, target); config.LoggingRules.Add(rule); LogManager.Configuration = config; //LogManager.DisableLogging(); }
static ProgramLogger() { var path = Path.Combine(DataLocation.DataDirectory(), DirectoryName, Constant.Version); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var configuration = new LoggingConfiguration(); var target = new FileTarget(); configuration.AddTarget("file", target); target.FileName = path.Replace(@"\", "/") + "/${shortdate}.txt"; #if DEBUG var rule = new LoggingRule("*", LogLevel.Debug, target); #else var rule = new LoggingRule("*", LogLevel.Error, target); #endif configuration.LoggingRules.Add(rule); LogManager.Configuration = configuration; }
public static void CreateConsoleLogger() { lock (_syncLock) { // 如果已經建立Logger物件, 就不重複建立 if (_logger != null) { return; } var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget("ConsoleLogger") { Layout = @"${date:format=MM-dd HH\:mm\:ss.fff} ${level} ${message}" }; config.AddTarget(consoleTarget); config.AddRuleForAllLevels(consoleTarget); LogManager.Configuration = config; _logger = LogManager.GetCurrentClassLogger(); } }
private void InitializeLoggerOnFirstCall() { if (_isInitialized) { return; } _isInitialized = true; LogManager.ThrowExceptions = true; var config = new LoggingConfiguration(); var target = new FileTarget() { CreateDirs = true, FileName = Path.Combine("logs", "easyfarm.log"), ArchiveOldFileOnStartup = true, MaxArchiveFiles = 5 }; config.AddTarget("LogSink", target); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, target)); LogManager.Configuration = config; }
public void Initialize() { // NUnit [Platform] attribute doesn't differentiate MacOSX/Linux if (Peach.Core.Platform.GetOS() != Peach.Core.Platform.OS.Linux) { Assert.Ignore("Only supported on Linux"); } ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget(); consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; LoggingConfiguration config = new LoggingConfiguration(); config.AddTarget("console", consoleTarget); LoggingRule rule = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; }
public void sixty8k() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Trace; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var sysLog = @"D:\SynologyDrive\EventLogs\DefConFS\Microsoft-Windows-TerminalServices-RemoteConnectionManager%4Admin.evtx"; var total = 0; using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } l.Info($"Total: {total}"); }
static void Main(string[] args) { var config = new LoggingConfiguration(); var target = new FileTarget { FileName = @"C:\Work\Logs\SupportBank.log", Layout = @"${longdate} ${level} - ${logger}: ${message}" }; config.AddTarget("File Logger", target); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target)); LogManager.Configuration = config; logger.Debug("Program started"); Console.Write("Enter filename: "); var fileName = Console.ReadLine(); while (!File.Exists("C:\\Work\\Training\\SupportBank-2018\\" + fileName)) { logger.Warn("User asked for file " + fileName + " which does not exist."); Console.WriteLine("File does not exist."); Console.Write("Enter filename: "); fileName = Console.ReadLine(); } logger.Debug("Found file " + fileName); var transactions = FileReader.ReadFile(fileName); var accounts = AccountProcessor.ProcessAccounts(transactions); logger.Debug("Getting user input"); Console.Write("Enter command: "); var input = Console.ReadLine(); var lowerInput = input.ToLowerInvariant(); input = TranslateInstructions(transactions, accounts, lowerInput); Console.ReadLine(); logger.Debug("Closing program"); }
public void ExcpetionTestAPI() { var config = new LoggingConfiguration(); var debugTarget = new DebugTarget(); config.AddTarget("debug1", debugTarget); debugTarget.Layout = @"${exception:format=shorttype,message:maxInnerExceptionLevel=3}"; var rule = new LoggingRule("*", LogLevel.Info, debugTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; string exceptionMessage = "Test exception"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.ErrorException("msg", ex); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine + "InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine + "InvalidOperationException Test exception"); #pragma warning restore 0618 logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine + "InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine + "InvalidOperationException Test exception"); var t = (DebugTarget)LogManager.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer; Assert.Equal(ExceptionRenderingFormat.ShortType, elr.Formats[0]); Assert.Equal(ExceptionRenderingFormat.Message, elr.Formats[1]); }
/// <summary> /// Create Custom Logger using parameters passed. /// </summary> /// <param name="name">Name of file.</param> /// <param name="LogEntryLayout">Give "" if you want just message. If omited will switch to full log paramaters.</param> /// <param name="logFileLayout">Filename only. No extension or file paths accepted.</param> /// <param name="absoluteFilePath">If you want to save the log file to different path thatn application default log path, specify the path here.</param> /// <returns>New instance of NLog logger completly isolated from default instance if any</returns> public static Logger CreateCustomLogger(string name = "CustomLog", string LogEntryLayout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss.fff} thread[${threadid}] ${logger} (${level:uppercase=true}): ${message}. ${exception:format=ToString}", string logFileLayout = "logs/{0}.${{shortdate}}.log", string absoluteFilePath = "") { var factory = new LogFactory(); var target = new FileTarget(); target.Name = name; if (absoluteFilePath == "") { target.FileName = string.Format(logFileLayout, name); } else { target.FileName = string.Format(absoluteFilePath + "//" + logFileLayout, name); } if (LogEntryLayout == "") //if user specifes "" then use default layout. { target.Layout = "${message}. ${exception:format=ToString}"; } else { target.Layout = LogEntryLayout; } var defaultconfig = LogManager.Configuration; var config = new LoggingConfiguration(); config.AddTarget(name, target); var ruleInfo = new LoggingRule("*", NLog.LogLevel.Trace, target); config.LoggingRules.Add(ruleInfo); factory.Configuration = config; return(factory.GetCurrentClassLogger()); }
public void ApplicationLog() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var sysLog = @"D:\SynologyDrive\EventLogs\HP_Spec\Application.evtx"; var total = 0; using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { // eventRecord.ConvertPayloadToXml(); } l.Info($"early : {es.EarliestTimestamp}"); l.Info($"last: {es.LatestTimestamp}"); } }
private static void ConfigureLogging() { LoggingConfiguration config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget { Layout = @"${message}" }; consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule { ForegroundColor = ConsoleOutputColor.Yellow, Condition = "level == LogLevel.Warn" }); consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Condition = "level == LogLevel.Error" }); consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule { ForegroundColor = ConsoleOutputColor.Green, Condition = "level == LogLevel.Info" }); consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule { ForegroundColor = ConsoleOutputColor.White, Condition = "level < LogLevel.Info" }); config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, consoleTarget)); LogManager.Configuration = config; }
public static void Initialize() { //var logFolder = Path.GetDirectoryName(AppExternal.UiControlledApp.ControlledApplication.RecordingJournalFilename); //if (string.IsNullOrEmpty(logFolder)) // Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //var logFile = Path.Combine(logFolder, "MDM_Revit.log"); //var fileName = string.Format(logFile); var logFilePath = "${specialfolder:folder=ApplicationData}/Program/RevitInventorLogFile.txt"; var fileTarget = new FileTarget { DeleteOldFileOnStartup = false, FileName = logFilePath, Layout = @"${longdate} ${level} Thread: [${threadname:whenEmpty=${threadid}}] ${message}", ArchiveAboveSize = 1024 * 1024, // 1MB ArchiveEvery = FileArchivePeriod.Day, MaxArchiveFiles = 20, ArchiveNumbering = ArchiveNumberingMode.Rolling, ArchiveFileName = logFilePath + ".{##}" }; var bufferTarget = new BufferingTargetWrapper { BufferSize = 100, WrappedTarget = fileTarget }; var rule = new LoggingRule("*", LogLevel.Debug, fileTarget); var config = new LoggingConfiguration(); config.AddTarget("bufferTarget", fileTarget); config.LoggingRules.Add(rule); //LogManager.Configuration = config; logger.Factory.Configuration = config; }
public RegistrosDeLogs(string stringDeConexaoDoBancoDeDados) { _stringDeConexaoDoBancoDeDados = stringDeConexaoDoBancoDeDados; const string origemDoRegistro = "RegistroDeLog"; var configuracaoDeLogging = new LoggingConfiguration(); var configuracoesDeBancoDeDados = new DatabaseTarget { Name = origemDoRegistro, ConnectionString = stringDeConexaoDoBancoDeDados, CommandText = "INSERT INTO RegistroDeLog (Id, Data, ThreadId, Logger, Level, Exception)" + "VALUES (NEWID(), GETDATE(), @threadId, @logger, @level, @exception)", Parameters = { new DatabaseParameterInfo { Name = "@threadId", Layout = "${threadid}" }, new DatabaseParameterInfo { Name = "@level", Layout = "${level}" }, new DatabaseParameterInfo { Name = "@logger", Layout = "${logger}" }, new DatabaseParameterInfo { Name = "@exception", Layout = "${message}" }, }, }; configuracaoDeLogging.AddTarget("bancoDeDados", configuracoesDeBancoDeDados); var regraDeLog = new LoggingRule("*", LogLevel.Trace, LogLevel.Off, configuracoesDeBancoDeDados); configuracaoDeLogging.LoggingRules.Add(regraDeLog); LogManager.Configuration = configuracaoDeLogging; _logger = LogManager.GetLogger(origemDoRegistro); }
internal virtual void Init() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); fileTarget.FileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\UIA.log"; // 20140312 fileTarget.AutoFlush = true; //fileTarget.Layout = "${date:format=HH\\:MM\\:ss}: ${message}"; //fileTarget.Layout = "[${date:format=DD/MM/YYYY HH\\:mm\\:ss}] [${}] ${message}"; //"${longdate}|${level:uppercase=true}|${logger}|${message}"; //fileTarget.Layout = "${longdate}|${level:uppercase=true}|${message}"; fileTarget.Layout = "[${longdate}] [${level:uppercase=true}] ${message}"; //fileTarget.Encoding = "iso-8859-2"; fileTarget.Encoding = System.Text.Encoding.Unicode; fileTarget.ConcurrentWriteAttempts = 3; fileTarget.ConcurrentWriteAttemptDelay = 2; fileTarget.CreateDirs = true; // 20140307 // var rule = new LoggingRule("*", NLog.LogLevel.Info, fileTarget); var rule = new LoggingRule("*", LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; UiaLogger = LogManager.GetLogger("UIA"); _alreadyInitialized = true; }
private void InitializeNLog() { var sdCard = Environment.ExternalStorageDirectory; var logDirectory = new File(sdCard.AbsolutePath + "/log"); logDirectory.Mkdirs(); var config = new LoggingConfiguration(); var csvFileTarget = new FileTarget { FileName = logDirectory.AbsolutePath + "/${shortdate}.csv" , Layout = new CsvLayout { Columns = { new CsvColumn("Time", "${longdate}"), new CsvColumn("Level", "${level}"), new CsvColumn("Lessage", "${message}"), new CsvColumn("Logger", "${logger}") }, } }; var lumberMillTarget = new LumberMillTarget(_androidId); config.AddTarget("CSV Logfile", csvFileTarget); config.AddTarget("Lumbermill Log", lumberMillTarget); var rule1 = new LoggingRule("*", LogLevel.Trace, csvFileTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", LogLevel.Trace, lumberMillTarget); config.LoggingRules.Add(rule2); LogManager.Configuration = config; _logger = LogManager.GetCurrentClassLogger(); _logger.Info("NLog successfully initialized."); _logger.Debug("Application starting up..."); }
/// <summary> /// Default initialization for on-premise paths /// </summary> private void InitializeForPremise() { // Replace log file and role name settings in the configuration var currentCfg = LogManager.Configuration; if (currentCfg == null) { Trace.WriteLine("No on-premise NLog configuration available - creating default config"); var level = global::NLog.LogLevel.Debug; var config = new LoggingConfiguration(); var console = new ColoredConsoleTarget() { UseDefaultRowHighlightingRules = true, Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}" }; var file = new FileTarget() { FileName = "${basedir}/application.log", Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}" }; var debug = new DebuggerTarget() { Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}" }; config.AddTarget("debug", debug); config.AddTarget("console", console); config.AddTarget("file", file); config.LoggingRules.Add(new LoggingRule("*", level, console)); config.LoggingRules.Add(new LoggingRule("*", level, file)); config.LoggingRules.Add(new LoggingRule("*", level, debug)); LogManager.Configuration = config; } else { Trace.WriteLine("Using NLog.config for non-Azure deployment"); } }
/// <summary> /// Updates a logging configuration for Azure compatability /// </summary> /// <param name="config"></param> public static void UpdateConfigForCloud(LoggingConfiguration config) { // Set up the azure role name variables // Add Azure role infomration to log4net properties var role = ConfigurationHelper.RoleName; var instance = ConfigurationHelper.InstanceName; // Update the file targets with the proper log storage directory base foreach (var ft in config.AllTargets.OfType<FileTarget>()) { var name = ft.Name.Replace("_wrapped", ""); // With Azure SDK 2.5 we can use absolute paths, not relative paths //var archiveFileName = String.Format("{0}Log_{1}_{2}_{3}_{{#####}}", // name, role, instance, @"${shortdate}.log"); //ft.ArchiveFileName = Path.Combine(archiveDirPath, archiveFileName); //var fileName = String.Format("{0}Log_{1}_{2}.log", // name, role, instance); //ft.FileName = Path.Combine(logDirPath, fileName); // Update the file targets with the role instance names for layout if (ft.Layout is CsvLayout) { var csvLayout = ft.Layout as CsvLayout; var roleCol = csvLayout.Columns.FirstOrDefault(e => e.Name == "role"); if (roleCol != null) roleCol.Layout = role; var instanceCol = csvLayout.Columns.FirstOrDefault(e => e.Name == "instance"); if (instanceCol != null) instanceCol.Layout = instance; } } // Add the trace listener when running in emulator if (RoleEnvironment.IsAvailable && RoleEnvironment.IsEmulated) { var trace = new global::NLog.Targets.TraceTarget(); trace.Name = "emulator_trace"; config.AddTarget("emulator_trace", trace); foreach (var rule in config.LoggingRules) { rule.Targets.Add(trace); } } }
public async Task TestCurrentManagedThreadIdMatchesCaller() { var loggingConfiguration = new LoggingConfiguration(); var target = new TestFileTarget(new CurrentManagedThreadIdLayout()); loggingConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal, target); LogManagerFactory.DefaultConfiguration = loggingConfiguration; var log = (ILoggerAsync)LogManagerFactory.DefaultLogManager.GetLogger<FileStreamingTargetTests>(); for (int i = 0; i < 100; i++) { var expectedThreadId = Environment.CurrentManagedThreadId; await log.TraceAsync("What thread am I?"); var output = target.Stream.ToArray(); target.Stream.Position = 0; var loggedThreadId = int.Parse(Encoding.UTF8.GetString(output, 0, output.Length)); Assert.Equal(expectedThreadId, loggedThreadId); } }
private static void SetupNLog() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; }