/// <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); }
private static LoggingConfiguration CreateConfigWithMemoryTarget(out MemoryTarget target, Layout layout) { var configuration = new LoggingConfiguration(); target = new MemoryTarget("target1") { Layout = layout }; configuration.AddRuleForAllLevels(target); return(configuration); }
private static LoggingConfiguration WriteToConsoleConfig() { var config = new LoggingConfiguration(); var target = new ColoredConsoleTarget("console") { Layout = @"[${date:format=HH\:mm\:ss} ${level}] ${message}${newline}${exception:format=ToString}" }; config.AddTarget(target); config.AddRuleForAllLevels(target); return(config); }
private static void UsingCodeConfiguration() { // Other overloads exist, for example, configure the SDK with only the DSN or no parameters at all. var config = new LoggingConfiguration(); config.AddSentry(options => { options.Layout = "${message}"; options.BreadcrumbLayout = "${logger}: ${message}"; // Optionally specify a separate format for breadcrumbs options.MinimumBreadcrumbLevel = NLog.LogLevel.Debug; // Debug and higher are stored as breadcrumbs (default is Info) options.MinimumEventLevel = NLog.LogLevel.Error; // Error and higher is sent as event (default is Error) // If DSN is not set, the SDK will look for an environment variable called SENTRY_DSN. If // nothing is found, SDK is disabled. options.Dsn = new Dsn("https://*****:*****@sentry.io/1340240"); options.AttachStacktrace = true; options.SendDefaultPii = true; // Send Personal Identifiable information like the username of the user logged in to the device options.IncludeEventDataOnBreadcrumbs = true; // Optionally include event properties with breadcrumbs options.ShutdownTimeoutSeconds = 5; options.AddTag("logger", "${logger}"); // Send the logger name as a tag options.HttpProxy = new WebProxy("http://127.0.0.1:8118", true) { UseDefaultCredentials = true }; // Other configuration }); config.AddTarget(new DebuggerTarget("Debugger")); config.AddTarget(new ColoredConsoleTarget("Console")); config.AddRuleForAllLevels("Console"); config.AddRuleForAllLevels("Debugger"); LogManager.Configuration = config; }
public void LogEventShouldCreateDatabase() { var database = new MockDatabase(); var configuration = new LoggingConfiguration(); var target = new SqlServerBulkTarget(database) { Name = "SqlServerBulk", ConnectionString = "[ConnectionString]", Table = "Log", LoggingColumns = new List <LoggingColumn> { new LoggingColumn { Name = "Message", SqlType = SqlType.NVARCHAR, Length = 10, Layout = "${message}" } } }; configuration.AddTarget(target); configuration.AddRuleForAllLevels("SqlServerBulk"); LogManager.Configuration = configuration; var Logger = LogManager.GetLogger("logger"); List <Exception> exceptions = new List <Exception>(); Logger.Info("message"); var expected = new[] { "SQL COMMAND: [ConnectionString] IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES\n" + " WHERE TABLE_CATALOG = DB_NAME()\n" + " AND TABLE_SCHEMA = @SchemaName\n" + " AND TABLE_NAME = @TableName\n" + " AND TABLE_TYPE = 'BASE TABLE')\n" + " CREATE TABLE [dbo].[Log] (\n" + " [Message] NVARCHAR(10))\n", "PARAMETER: @SchemaName=(String)dbo", "PARAMETER: @TableName=(String)Log", "BULK INSERT: [ConnectionString] Log", "ROW: Message=(String)message" }; for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], database.Log[i]); } }
/// <summary> /// <para>en: Initialization configuration for writing to file </para> /// <para>vi: Cấu hình khởi tạo để ghi vào tập tin</para> /// </summary> public static void Initialization(bool Info = true, bool Debug = true, bool Warn = true, bool Error = true, bool Trace = true, bool Off = true, bool Fatal = true) { LoggingConfiguration config = new LoggingConfiguration(); //config for console log ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget("ConsoleTarget") { Layout = "${longdate}|${level}|${message}${callsite:className=false:fileName=true:includeSourcePath=false:methodName=false}|${exception}" }; config.AddTarget(consoleTarget); //config for file log FileTarget fileTarget = new FileTarget("FileTarget") { FileName = "${basedir}/logs/${date:format=yyyy_MM_dd}.log", Layout = "${longdate}|${level}|${message}${callsite:className=false:fileName=true:includeSourcePath=false:methodName=false}|${exception}" }; config.AddTarget(fileTarget); // errors and warning write to file if (Info) { config.AddRuleForOneLevel(LogLevel.Info, fileTarget); } if (Error) { config.AddRuleForOneLevel(LogLevel.Error, fileTarget); } if (Warn) { config.AddRuleForOneLevel(LogLevel.Warn, fileTarget); } if (Debug) { config.AddRuleForOneLevel(LogLevel.Debug, fileTarget); } if (Fatal) { config.AddRuleForOneLevel(LogLevel.Fatal, fileTarget); } if (Off) { config.AddRuleForOneLevel(LogLevel.Off, fileTarget); } if (Trace) { config.AddRuleForOneLevel(LogLevel.Trace, fileTarget); } // all to console config.AddRuleForAllLevels(consoleTarget); //Activate the configuration LogManager.Configuration = config; }
private LoggingConfiguration BuildNLogConfiguration([CanBeNull] string logPath) { var config = new LoggingConfiguration(); var aiKey = Environment.GetEnvironmentVariable( LoggingConstants.ApplicationInsightsInstrumentationKeyEnvironmentVariableName); if (!string.IsNullOrWhiteSpace(aiKey)) { var aiTarget = new ApplicationInsights.NLogTarget.ApplicationInsightsTarget() { Name = "ai", InstrumentationKey = aiKey, }; config.AddTarget(aiTarget); config.AddRuleForAllLevels(aiTarget); } bool hasLogPath = !string.IsNullOrWhiteSpace(logPath); if (hasLogPath || config.AllTargets.Count == 0) { if (!hasLogPath) { logPath = LoggingConstants.DefaultLogPath; } // Default layout: "${longdate}|${level:uppercase=true}|${logger}|${message}" var fileTarget = new NLog.Targets.FileTarget("file") { FileName = Path.GetFullPath(logPath), Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}${exception:format=ToString}", }; config.AddTarget(fileTarget); config.AddRuleForAllLevels(fileTarget); } return(config); }
public static void InitializeLogger() { LoggingConfiguration config = new LoggingConfiguration(); TargetWithLayout target = new InvocableMemoryTarget(INVOCABLE_MEMORY_TARGET_NAME, MEMORY_TARGET_NAME) { Layout = "${shortdate} ${time} [${level:format=FullName}] ${message}" // https://nlog-project.org/config/?tab=layout-renderers }; config.AddRuleForAllLevels(target); LogManager.Configuration = config; }
#pragma warning disable CA2000 // Dispose objects before losing scope private static LoggingConfiguration SetupNLogConfig() { var logConfig = new LoggingConfiguration(); var coloredConsoleTarget = new ColoredConsoleTarget("logconsole") { Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} ${logger:shortName=True} | ${message} ${exception}" }; logConfig.AddTarget(coloredConsoleTarget); var debugTarget = new DebuggerTarget { Name = "debugConsole", Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} ${logger:shortName=True} | ${message} ${exception}" }; logConfig.AddTarget(debugTarget); var fileTarget = new FileTarget { Name = "logFile", Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} ${logger:shortName=True} | ${message} ${exception}", FileName = "${basedir}/Logs/${level}.log", ArchiveFileName = "${basedir}/Logs/Archive/${level}.{##}.log", ArchiveNumbering = ArchiveNumberingMode.Sequence, ArchiveAboveSize = 1_000_000, ConcurrentWrites = false, MaxArchiveFiles = 20 }; logConfig.AddTarget(fileTarget); logConfig.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Fatal, coloredConsoleTarget); logConfig.AddRuleForAllLevels(debugTarget); logConfig.AddRuleForAllLevels(fileTarget); return(logConfig); }
public void FluentDelegateConfiguration() { var configuration = new LoggingConfiguration(); string expectedMessage = "Hello World"; string actualMessage = string.Empty; configuration.AddRuleForAllLevels(new MethodCallTarget("Hello", (logEvent, parameters) => { actualMessage = logEvent.Message; })); LogManager.Configuration = configuration; LogManager.GetCurrentClassLogger().Debug(expectedMessage); Assert.Equal(expectedMessage, actualMessage); }
/// <inheritdoc /> public Class1() { // setup config var configuration = new LoggingConfiguration(); configuration.AddRuleForAllLevels(new ConsoleTarget()); LogManager.Configuration = configuration; // log Logger logger = LogManager.GetCurrentClassLogger(); logger.Info("Init class1"); }
private static void ConfigureLogging() { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget("target1") { Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" }; config.AddTarget(consoleTarget); config.AddRuleForAllLevels(consoleTarget); // all to console LogManager.Configuration = config; }
private LoggingConfiguration GetLoggingConfiguration() { LoggingConfiguration configuration = new LoggingConfiguration(); configuration.AddTarget(new FileTarget("LogFile") { Layout = "${longdate} ${logger} ${message}${exception:format=ToString}", FileName = "${basedir}/logs/Debug.log", Encoding = Encoding.UTF8 }); configuration.AddRuleForAllLevels("LogFile"); return(configuration); }
private void ConfigureNlog() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget(nameof(AkkaLoggingByDedicatedAddNLogExtension) + "Target") { FileName = LogPath, Layout = @"[${level}][${longdate}][${stacktrace:format=Flat}]${literal:text=[Exception\: :when=length('${exception}')>0}${exception}${literal:text=]:when=length('${exception}')>0} <${message}>", }; config.AddTarget(fileTarget); config.AddRuleForAllLevels(fileTarget); LogManager.Configuration = config; }
static void ConfigureLogging() { var config = new LoggingConfiguration(); var target = new FileTarget { AutoFlush = true, FileName = "ErrorLog.txt", DeleteOldFileOnStartup = true }; config.AddRuleForAllLevels(target); LogManager.Configuration = config; }
public static void ConfigureAndAddLoggingTarget(TargetWithLayout target, LoggingConfiguration loggingConfiguration) { target.Layout = Layout.FromString( //bug FromMethod allows even more customization "${longdate}" + "|${event-properties:item=EventId_Id:whenEmpty=0}" + "|${uppercase:${level}}" + "|${logger}" + "|${message} ${exception:format=tostring}" + "|requestId=${mdlc:item=requestId}" + "|operationName=${mdlc:item=operationName}" + "|customerId=${mdlc:item=customerId}"); loggingConfiguration.AddRuleForAllLevels(target); }
static void Main(string[] args) { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets var consoleTarget = new ColoredConsoleTarget("target1") { Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" }; config.AddTarget(consoleTarget); var fileTarget = new FileTarget("target2") { FileName = "${basedir}/file.txt", Layout = "${longdate} ${level} ${message} ${exception}" }; config.AddTarget(fileTarget); // Step 3. Define rules config.AddRuleForOneLevel(LogLevel.Error, fileTarget); // only errors to file config.AddRuleForAllLevels(consoleTarget); // all to console // Step 4. Activate the configuration LogManager.Configuration = config; // Example usage Logger logger = LogManager.GetLogger("Example"); logger.Trace("trace log message"); logger.Debug("debug log message"); logger.Info("info log message"); logger.Warn("warn log message"); logger.Error("error log message"); logger.Fatal("fatal log message"); //Example of logging exceptions try { } catch (Exception ex) { logger.Error(ex, "ow noos!"); throw; } }
public static void InitializePluginLogging(EAAPI.Repository repository, string logTabName = "System") { LoggingConfiguration loggingConfig = new LoggingConfiguration(); EaPluginNlogTarget eaPluginNlogTarget = new EaPluginNlogTarget(repository, logTabName); loggingConfig.AddTarget(eaPluginNlogTarget); loggingConfig.AddRuleForAllLevels(eaPluginNlogTarget); LogManager.Configuration = loggingConfig; repository.EnsureOutputVisible(logTabName); }
public void Dsn_SupportsNLogLayout_Lookup() { var expectedDsn = "https://[email protected]/1"; var target = (SentryTarget)_fixture.GetTarget(); target.Dsn = "${var:mydsn}"; var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); logConfig.Variables["mydsn"] = expectedDsn.ToString(); logConfig.AddRuleForAllLevels(target); logFactory.Configuration = logConfig; Assert.Equal(expectedDsn.ToString(), target.Options.Dsn.ToString()); }
private static LoggingConfiguration CreateConfigWithMemoryTarget(out MemoryTarget memoryTarget, string levelMessage = "${level}|${message}", LogFactory logFactory = null) { var config = new LoggingConfiguration(logFactory); memoryTarget = new MemoryTarget { Layout = levelMessage }; config.AddRuleForAllLevels(memoryTarget); if (logFactory != null) { logFactory.Configuration = config; } return(config); }
public static void Configure() { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget("console") { Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss} ${level:uppercase=true} ${logger:shortName=true}: ${message:WithException=true}" }; config.AddTarget(consoleTarget); config.AddRuleForAllLevels(consoleTarget); LogManager.Configuration = config; }
public void LogMessageWithNestedObjects_UserModifiedRecursionLimit() { //Arrange // For this one-off test, need to re-do the logging configuration to override what is done in setup var target = new DebugTarget("customAttributeTarget"); var layout = new NewRelicJsonLayout(() => _testAgent); layout.MaxRecursionLimit = 3; target.Layout = layout; var config = new LoggingConfiguration(); config.AddTarget(target); config.AddRuleForAllLevels(target); LogManager.Configuration = config; var logger = LogManager.GetLogger("customAttributeLogger"); var alice = new Person { Name = "Alice", Manager = null }; var bob = new Person { Name = "Bob", Manager = alice }; var charlie = new Person { Name = "Charlie", Manager = bob }; var messageTemplate = "Person = {person}"; var formattedMessage = "Person = Charlie"; //Act logger.Info(messageTemplate, charlie); var loggedMessage = target.LastMessage; var resultsDictionary = TestHelpers.DeserializeOutputJSON(loggedMessage); //Assert Asserts.KeyAndValueMatch(resultsDictionary, NewRelicLoggingProperty.MessageText.GetOutputName(), formattedMessage); Asserts.KeyAndValueMatch(resultsDictionary, NewRelicLoggingProperty.MessageTemplate.GetOutputName(), messageTemplate); Assert.IsTrue(resultsDictionary.ContainsKey(UserPropertiesKey)); Asserts.KeyAndValueMatch(resultsDictionary, UserPropertiesKey, JsonValueKind.Object); var userPropertiesDict = TestHelpers.DeserializeOutputJSON(resultsDictionary[UserPropertiesKey].ToString()); Asserts.KeyAndValueMatch(userPropertiesDict, "person", JsonValueKind.Object); var userPropValDict = TestHelpers.DeserializeOutputJSON(userPropertiesDict["person"].ToString()); Asserts.KeyAndValueMatch(userPropValDict, "Name", "Charlie"); Asserts.KeyAndValueMatch(userPropValDict, "Manager", JsonValueKind.Object); }
public Logger() { var config = new LoggingConfiguration(); string layout = LoggerConfig.Layout; //控制台 if (GlobalSwitch.LoggerType.HasFlag(LoggerType.Console)) { AddTarget(new ColoredConsoleTarget { Name = LoggerConfig.LoggerName, Layout = layout }); } //文件 if (GlobalSwitch.LoggerType.HasFlag(LoggerType.File)) { AddTarget(new FileTarget { Name = LoggerConfig.LoggerName, Layout = layout, FileName = Path.Combine(Directory.GetCurrentDirectory(), "logs", "${date:format=yyyy-MM-dd}.txt") }); } //数据库 if (GlobalSwitch.LoggerType.HasFlag(LoggerType.RDBMS)) { AddTarget(new RDBMSTarget { Layout = layout }); } //ElasticSearch if (GlobalSwitch.LoggerType.HasFlag(LoggerType.ElasticSearch)) { AddTarget(new ElasticSearchTarget { Layout = layout }); } NLog.LogManager.Configuration = config; void AddTarget(Target target) { config.AddTarget(target); config.AddRuleForAllLevels(target); } }
public static void Initialize() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget("fileTarget") { Encoding = Encoding.UTF8, FileName = "Geolocation.log", Layout = "${longdate} ${level:uppercase=true}\t${logger}\n${message}\n" }; config.AddTarget(fileTarget); config.AddRuleForAllLevels(fileTarget); LogManager.Configuration = config; }
private WorkspaceLogger() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget() { Name = "File", FileName = "${specialfolder:folder=LocalApplicationData}/TaskWorkspace/logs/${shortdate}.log", Layout = "${longdate} ${logger} ${uppercase:${level}} ${message}${exception:format=ToString}", }; config.AddTarget(fileTarget); config.AddRuleForAllLevels(fileTarget); LogManager.Configuration = config; Logger = LogManager.GetLogger("TaskWorkspace"); }
/// <summary> /// ## BootstrapLogger /// /// Sets up the logger to log pipeline execution. /// </summary> /// <param name="logToFile"></param> /// <param name="directory"></param> private void BootstrapLogger(bool logToFile, string directory) { LoggingConfiguration config = new LoggingConfiguration(); if (logToFile) { FileTarget fileTarget = new FileTarget("file") { FileName = Path.Combine(directory, "logs", "paku.log"), ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMdd" }; config.AddRuleForAllLevels(fileTarget); } else { config.AddTarget(new NullTarget("null")); config.AddRuleForAllLevels("null"); } LogManager.Configuration = config; this.Logger = LogManager.GetLogger("Paku"); }
public LoggerHelper(string filePath, string name) { LoggingConfiguration Config = new LoggingConfiguration(); FileTarget fileTarget = new FileTarget("fileTarget") { FileName = $"{filePath}/{name}.txt", Layout = "${longdate} ${level} ${message} ${exception}" }; Config.AddTarget(fileTarget); Config.AddRuleForAllLevels(fileTarget); LogManager.Configuration = Config; Log = LogManager.GetLogger("logger"); }
static QLog() { //#if DEBUG // // Setup the logging view for Sentinel - http://sentinel.codeplex.com // var sentinalTarget = new NLogViewerTarget() // { // Name = "sentinal", // Address = "udp://127.0.0.1:9999", // IncludeNLogData = false // }; // var sentinalRule = new LoggingRule("*", LogLevel.Trace, sentinalTarget); // LogManager.Configuration.AddTarget("sentinal", sentinalTarget); // LogManager.Configuration.LoggingRules.Add(sentinalRule); // // Setup the logging view for Harvester - http://harvester.codeplex.com // var harvesterTarget = new OutputDebugStringTarget() // { // Name = "harvester", // Layout = "${log4jxmlevent:includeNLogData=false}" // }; // var harvesterRule = new LoggingRule("*", LogLevel.Trace, harvesterTarget); // LogManager.Configuration.AddTarget("harvester", harvesterTarget); // LogManager.Configuration.LoggingRules.Add(harvesterRule); //#endif var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget("target1") { Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" }; var fileTarget = new FileTarget("target2") { FileName = AppDomain.CurrentDomain.BaseDirectory + "run.log", Layout = "${longdate} ${level} ${message} ${exception}" }; config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget); // add to file config.AddRuleForAllLevels(consoleTarget); // all to console NLog.LogManager.Configuration = config; Task.Run(() => { logger = LogManager.GetCurrentClassLogger(); waitHandle.Set(); }); }
/// <summary> /// Default constructor /// </summary> public NLogLogger() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget("NLogFile") { FileName = "${basedir}/NLogFile.log", Layout = "${longdate} ${level} ${message} ${exception}" }; config.AddTarget(fileTarget); config.AddRuleForAllLevels(fileTarget); LogManager.Configuration = config; _logger = LogManager.GetCurrentClassLogger(); }
private static LogFactory ConfigureLogFactory(string folder) { var logConf = new LoggingConfiguration(); var fileTarget = new FileTarget { FileName = Path.Combine(folder, "log.txt"), CreateDirs = true, Name = "TargetLog", Layout = "${date} ${message} ${onexception:inner=${exception:format=toString}}" }; logConf.AddTarget(fileTarget); logConf.AddRuleForAllLevels(fileTarget); return(new LogFactory(logConf)); }