public void TestTagListWildcard() { var config = new LoggingConfig(); config.LoadConfig(); var dispatcher = new LogEventDispatcher(config); var tagKeeper = dispatcher.TagKeeper; Assert.IsTrue(tagKeeper.CheckMatch("helloworld", "hello*")); }
public void TestSimpleEmail() { var config = new LoggingConfig(@"Configs\SimpleEmailTest.json"); LoggerFactory.Initialize(config); var logger = LoggerFactory.GetLogger(); logger.Log("Hello, World!"); }
/// <summary> /// Updates the given configuration, adding the traditional log levels as tag groups to the configuration /// </summary> /// <param name="loggingConfig">The logging config to update</param> public void UpdateConfig(LoggingConfig loggingConfig) { if (loggingConfig != null) { if (loggingConfig.TagGroups == null) loggingConfig.TagGroups = new List<TagGroupConfig>(); var missingTagGroups = _tagGroupConfigs.Where(nx => loggingConfig.TagGroups.Any(ox => ox.Tag == nx.Tag) == false); foreach (var missingTagGroup in missingTagGroups) loggingConfig.TagGroups.Add(missingTagGroup); } }
public void TestTagList() { var config = new LoggingConfig(); config.LoadConfig(); var dispatcher = new LogEventDispatcher(config); var tagList = new List<string> { "fatal", "error", "warn", "info", "debug", "trace" }; var tagKeeper = dispatcher.TagKeeper; for (int lp = 0; lp < tagList.Count - 1; lp++) for (int lp2 = lp + 1; lp2 < tagList.Count; lp2++) Assert.IsTrue(tagKeeper.CheckMatch(tagList[lp], tagList[lp2]), String.Format("Checking {0} = {1}", tagList[lp2], tagList[lp])); }
public void MalformedJSONTest() { // Initialize the failure test ConfigFailed = false; var config = new LoggingConfig() { ExceptionHandler = HandleException }; ICollection<string> sourceLines; using (var copy = new ConfigFileCopy(DefaultConfigFile)) { // Load the file config.LoadConfig(copy.FileName); // Break the file sourceLines = MalformnJSON(copy.FileName); // Check to see if the failure was detected int checkCount = 0; while (!ConfigFailed) { Thread.Sleep(200); if (checkCount++ > 5) break; } Assert.IsTrue(ConfigFailed); // Next we need to see if we can recover from the error // Restore the file WriteFile(copy.FileName, sourceLines); // Make sure that watch is on Assert.IsTrue(config.Watch); // Turn off watch SetWatch(copy.FileName, false); for (int lp = 0; lp < 10; lp++) { if (!config.Watch) break; Thread.Sleep(100); } // Make sure watch is off Assert.IsFalse(config.Watch); } }
public void TestSimpleIncludeRule() { var config = new LoggingConfig(); config.LoadConfig(@"Configs\SimpleIncludeRuleTest.json"); var dispatcher = new LogEventDispatcher(config); var ruleKeeper = dispatcher.RuleKeeper; var infoTargets = ruleKeeper.GetTargetsForTags(new List<string> { "info" }); Assert.IsNotNull(infoTargets); Assert.IsTrue(infoTargets.Count == 1); Assert.IsTrue(infoTargets.Contains("console")); var traceTargets = ruleKeeper.GetTargetsForTags(new List<string> { "trace" }); Assert.IsNotNull(traceTargets); Assert.IsTrue(traceTargets.Count == 0); }
public void TestStrictIncludeRule() { var config = new LoggingConfig(); config.LoadConfig(@"Configs\StrictIncludeRuleTest.json"); var dispatcher = new LogEventDispatcher(config); var ruleKeeper = dispatcher.RuleKeeper; var strictTargets = ruleKeeper.GetTargetsForTags(new List<string> { this.GetType().FullName, "info" }); Assert.IsNotNull(strictTargets); Assert.IsTrue(strictTargets.Count == 1); Assert.IsTrue(strictTargets.Contains("console")); var incompleteTargets = ruleKeeper.GetTargetsForTags(new List<string> { "info" }); Assert.IsNotNull(incompleteTargets); Assert.IsTrue(incompleteTargets.Count == 0); }
public void WatchTest() { using (var copy = new ConfigFileCopy(DefaultConfigFile)) { var config = new LoggingConfig(); config.LoadConfig(copy.FileName); Assert.IsTrue(config.Watch); SetWatch(copy.FileName, false); for (int lp = 0; lp < 50; lp++) { if (!config.Watch) break; Thread.Sleep(100); } Assert.IsFalse(config.Watch); } }
public void UpdateConfig(LoggingConfig loggingConfig) { // Make sure targets exists if (loggingConfig.Targets == null) loggingConfig.Targets = new List<TargetConfig>(); // Add our target if it doesn't yet exist if (!loggingConfig.Targets.Any(_ => _.Name == MyCustomTargetName)) { loggingConfig.Targets.Add(ConsoleTargetConfigBuilder.Create() .SetName(MyCustomTargetName) .AddConsoleColorRule(new ConsoleColorRule { Tags = new string[] { MyCustomRuleInclude }, BackgroundColor = MyCustomBackgroundColor, ForegroundColor = MyCustomForegroundColor }) .Build()); } // Make sure rules exist if (loggingConfig.Rules == null) loggingConfig.Rules = new List<RuleConfig>(); // Add our rule if it doesn't yet exist if (!loggingConfig.Rules.Any(_ => _.Include != null && _.Include.Count == 1 && _.Include.Contains(MyCustomRuleInclude) && _.WriteTo != null && _.WriteTo.Count == 1 && _.WriteTo.Contains(MyCustomTargetName))) loggingConfig.Rules.Add(RuleConfigBuilder.CreateRuleConfig() .AddInclude(MyCustomRuleInclude) .AddWriteTo(MyCustomTargetName) .Build()); }
public void TestMultipleRule() { var config = new LoggingConfig(); config.LoadConfig(@"Configs\MultipleRuleTest.json"); var dispatcher = new LogEventDispatcher(config); var ruleKeeper = dispatcher.RuleKeeper; var cond1Targets = ruleKeeper.GetTargetsForTags(new List<string> { "cond1" }); Assert.IsNotNull(cond1Targets); Assert.IsTrue(cond1Targets.Count == 2); Assert.IsTrue(cond1Targets.Contains("target1")); Assert.IsTrue(cond1Targets.Contains("target2")); var cond2Targets = ruleKeeper.GetTargetsForTags(new List<string> { "cond2" }); Assert.IsNotNull(cond2Targets); Assert.IsTrue(cond2Targets.Count == 1); Assert.IsTrue(cond2Targets.Contains("target2")); var cond3Targets = ruleKeeper.GetTargetsForTags(new List<string> { "cond3" }); Assert.IsNotNull(cond3Targets); Assert.IsTrue(cond3Targets.Count == 1); Assert.IsTrue(cond3Targets.Contains("target1")); }
/// <summary> /// Notifies this dispatcher of a new configuration /// </summary> /// <param name="loggingConfig">The new configuration</param> public void NotifyNewConfig(LoggingConfig loggingConfig) { NewConfig(loggingConfig); }
public void TestComplexRule() { var config = new LoggingConfig(); config.LoadConfig(@"Configs\ComplexRuleTest.json"); var dispatcher = new LogEventDispatcher(config); var ruleKeeper = dispatcher.RuleKeeper; var infoTargets = ruleKeeper.GetTargetsForTags(new List<string> { "info", this.GetType().FullName }); Assert.IsNotNull(infoTargets); Assert.IsTrue(infoTargets.Count == 1); Assert.IsTrue(infoTargets.Contains("console")); var traceTargets = ruleKeeper.GetTargetsForTags(new List<string> { "trace", this.GetType().FullName }); Assert.IsNotNull(traceTargets); Assert.IsTrue(traceTargets.Count == 0); var infoTargetTargets = ruleKeeper.GetTargetsForTags(new List<string> { "info", "NuLog.Targets", this.GetType().FullName }); Assert.IsNotNull(infoTargetTargets); Assert.IsTrue(infoTargetTargets.Count == 0); }
public void InitializeTest() { var config = new LoggingConfig(); config.LoadConfig(); }
/// <summary> /// Notifies this TagKeeper of a new logging config /// </summary> /// <param name="loggingConfig">The new logging config</param> public void NotifyNewConfig(LoggingConfig loggingConfig) { lock (_tagLock) { UpdateTagGroups(TagGroups, loggingConfig.TagGroups); } }
/// <summary> /// Initializes this extender with the provided configuration /// </summary> /// <param name="extenderConfig">The configuration for this specific extender</param> /// <param name="loggingConfig">The whole configuration for the framework</param> public override void Initialize(ExtenderConfig extenderConfig, LoggingConfig loggingConfig) { // Let the base configure itself out base.Initialize(extenderConfig, loggingConfig); // Configure this extender, using the TraceListenerConfig if (extenderConfig != null) { TraceListenerConfig = extenderConfig is TraceListenerConfig ? (TraceListenerConfig)extenderConfig : new TraceListenerConfig(extenderConfig.Config); } }
/// <summary> /// Initializes the logging framework using a file /// </summary> /// <param name="configFile">The path to the JSON configuration file to use</param> /// <param name="dispatcher">An alternate dispatcher to use for the logging framework</param> /// <param name="exceptionHandler">An exception handler to use for debugging purposes</param> /// <param name="force">Whether or not to force the re-configuration if the framework has alredy been intiaizlied</param> public static void Initialize(string configFile, LogEventDispatcher dispatcher = null, Action<Exception, string> exceptionHandler = null, bool force = true) { LoggingConfig config = null; // Try to load the config from the given file try { config = new LoggingConfig(configFile); } catch (Exception cause) { // Report the exception if (exceptionHandler != null) { exceptionHandler(cause, ConfigurationFailedUsingDefaultsMessage); } else { Trace.WriteLine(cause, TraceConfigCategory); } } Initialize(config, dispatcher, exceptionHandler, force); }
/// <summary> /// Initializes the logging framework using a provided LoggingConfig /// </summary> /// <param name="config">The LoggingConfig to use to initialize the logging framework</param> /// <param name="dispatcher">An alternate dispatcher to use for the logging framework</param> /// <param name="exceptionHandler">An exception handler to use for debugging purposes</param> /// <param name="force">Whether or not to force the re-configuration if the framework has alredy been intiaizlied</param> public static void Initialize(LoggingConfig config = null, LogEventDispatcher dispatcher = null, Action<Exception, string> exceptionHandler = null, bool force = true) { lock (_factoryLock) { var instance = Instance.Value; // We only want to configure if we haven't yet, or if it is marked to override (force) the initialization if (force || !instance.Initialized) { // Shutdown existing config if it exists if (instance.Initialized) instance.LoggingConfig.Shutdown(); // Wire up the exception handler instance.ExceptionHandler = exceptionHandler; // Setup the logging config instance.InitializeConfig(config); // Load and initialize the extenders, allowing them to update the config // before we start instance.InitializeExtenders(); // Setup the dispatcher instance.InitializeDispatcher(dispatcher); // Start the extenders instance.StartExtenders(instance.LogEventDispatcher); // Mark us as initialized instance.Initialized = true; } } }
/// <summary> /// Gives this extender the opportunity to extend the given logging configuration before it is used to initialize the objects in the framework /// </summary> /// <param name="loggingConfig">The logging config to update</param> public virtual void UpdateConfig(LoggingConfig loggingConfig) { // Do nothing }
/// <summary> /// An internal function for initializing the logging config for the factory /// </summary> /// <param name="config">The config to use for initialization. If none(null) provided, the default logging config will be loaded (from NuLog.json)</param> private void InitializeConfig(LoggingConfig config = null) { // The configuration needs to be shutdown because it has a list of observers // and may have a file-watcher implemented that needs to be disabled/shutdown if (Initialized) LoggingConfig.Shutdown(); // Make sure that the MEF extensions are loaded in InitializeMEF(); try { // Load using the supplied config, // or the default config from the default config builder // or the default config as defined by LoggingConfig LoggingConfig = config != null ? config : DefaultConfigBuilder != null ? DefaultConfigBuilder.Build() : new LoggingConfig(); } catch (Exception cause) { // Report the exception Trace.WriteLine(ConfigurationFailedUsingDefaultsMessage); Trace.WriteLine(String.Format(ConfigLoadFailureMessage, cause.Message, cause.StackTrace), TraceConfigCategory); // Load the default config to get us off the ground!! LoggingConfig = new LoggingConfig(loadConfig: false); } // Load the config extenders LoadConfigExtenders(); // Execute the config extenders against the configuration ExecuteConfigExtenders(); }
/// <summary> /// Notifies this rule keeper of a new configuration /// </summary> /// <param name="loggingConfig">The new configuration</param> public void NotifyNewConfig(LoggingConfig loggingConfig) { lock (_ruleLock) { // If rules are defined, assign them if (loggingConfig.Rules != null && loggingConfig.Rules.Count > 0) { Rules = loggingConfig.Rules; } else { // Otherwise, route everything everywhere var newRule = RuleConfigBuilder.CreateRuleConfig() .AddWriteTo("*") .Build(); Rules = new List<RuleConfig> { newRule }; } // Clear the cache _routeKeyCache.Clear(); _routeCache.Clear(); } }
/// <summary> /// Reconfigures the dispatcher with the new logging config /// </summary> /// <param name="loggingConfig">The new logging config for the dispatcher</param> public void NewConfig(LoggingConfig loggingConfig) { // Store the new config LoggingConfig = loggingConfig; // Start or stop the thread depending on the configuration ConfigureThread(); // Load Our Static Meta Data Providers LoadStaticMetaDataProviders(); // Notify our dependents of the new config lock (LoggingLock) { // Notify the different keepers of the new config TagKeeper.NotifyNewConfig(loggingConfig); TargetKeeper.NotifyNewConfig(loggingConfig); RuleKeeper.NotifyNewConfig(loggingConfig); // And clear the target cache TargetCache.Clear(); } }
/// <summary> /// Builds the dispatcher using the provided configuration and optional exception handler /// </summary> /// <param name="initialConfig">The initial configuration to use to build the dispatcher</param> /// <param name="exceptionHandler">The exception handler to use for the dispatcher</param> public LogEventDispatcher(LoggingConfig initialConfig, Action<Exception, string> exceptionHandler = null) { ExceptionHandler = exceptionHandler; TagKeeper = new TagKeeper(); TargetKeeper = new TargetKeeper(this); RuleKeeper = new RuleKeeper(TagKeeper); TargetCache = new Dictionary<string, ICollection<TargetBase>>(); ActionQueue = new ConcurrentQueue<Action>(); LogQueue = new ConcurrentQueue<LogEvent>(); // Wire up the configuration NewConfig(initialConfig); }
/// <summary> /// Initializes the extender with the given configuration objects /// </summary> /// <param name="extenderConfig">The configuration for this extender</param> /// <param name="loggingConfig">The whole configuration</param> public virtual void Initialize(ExtenderConfig extenderConfig, LoggingConfig loggingConfig) { ExtenderConfig = extenderConfig; LoggingConfig = loggingConfig; }
/// <summary> /// Notifies this target keeper of a new logging config /// </summary> /// <param name="loggingConfig">The new logging config</param> public void NotifyNewConfig(LoggingConfig loggingConfig) { lock (_configLock) { LoggingConfig = loggingConfig; lock (_targetLock) { Type targetType; ConstructorInfo constructorInfo; TargetBase newTarget; // Iterate over each of the targets to figure out how to handle each one if (loggingConfig.Targets != null && loggingConfig.Targets.Count > 0) { foreach (var targetConfig in loggingConfig.Targets) { // Retrieve the target by name and unregister it // The unregister function handles a null (not found) // existing target var oldTarget = (from target in _targets where target.Key == targetConfig.Name select target.Value).SingleOrDefault(); UnregisterTarget(oldTarget); try { // Build, initialize and registyer a new instance of // the target based on its represented "Type" targetType = Type.GetType(targetConfig.Type); if (targetType != null) { constructorInfo = targetType.GetConstructor(new Type[] { }); newTarget = (TargetBase)constructorInfo.Invoke(null); newTarget.Initialize(targetConfig, Dispatcher, loggingConfig.Synchronous ? (bool?)true : null); RegisterTarget(newTarget); } else { throw new LoggingException(String.Format("Type not found for {0}", targetConfig.Type)); } } catch (Exception exception) { // If we failed to register the new target, // re-register the old one and handle the // exception RegisterTarget(oldTarget); HandleException(exception); } } // Determine which targets are no longer defined // in the configuration and unregister them var droppedTargets = _targets.Where(_ => !loggingConfig.Targets.Any(c => c.Name == _.Value.Name)).ToList(); foreach (var droppedTarget in droppedTargets) { try { UnregisterTarget(droppedTarget.Value); } catch (Exception exception) { HandleException(exception); } } } else { // If no targets were defined, drop the existing registered targets var droppedTargets = _targets.Where(_ => _.Value.Name == "target").ToList(); foreach (var droppedTarget in droppedTargets) { try { UnregisterTarget(droppedTarget.Value); } catch (Exception exception) { HandleException(exception); } } // Register a single trace target if (_targets.ContainsKey("target") == false) { newTarget = new TraceTarget("target"); RegisterTarget(newTarget); } } // Clear the list of compiled targets _compiledTargets.Clear(); } } }