public static void Initiate() { if (!initiated) { logging = new LoggingSection("Services"); CommandHandler = new CommandHandler(); Scanners = new Scanners(); OCRProvider = new ConcurrentResourceProvider <TesseractEngine>(); TesseractEngine[] tesseractEngine = new TesseractEngine[Environment.ProcessorCount]; for (int i = 0; i < tesseractEngine.Length; i++) { tesseractEngine[i] = new TesseractEngine(@"./Tesseract/tessdata", "deu"); } OCRProvider.Setup(tesseractEngine); servicesToBeDisposed = new List <IDisposable>() { CommandHandler, OCRProvider }; initiated = true; logging.Info("Services initiation complete"); } }
public async Task <ScanResult> ScanAsync(string filename) { FileInfo fileInfo = new FileInfo(filename); LoggingSection log = logging.CreateChild(fileInfo.Name); log.Verbose($"Starting {GetType().Name} on {fileInfo.FullName}"); DateTime timeStarted = DateTime.Now; string result = null; bool succeeded; Exception exception = null; try { result = await DoScanAsync(fileInfo.FullName, log); succeeded = true; log.Verbose("Scan was successfull"); } catch (Exception e) { succeeded = false; exception = e; log.Warning($"Scan failed: {e.Message}{Environment.NewLine}{e.StackTrace}"); } DateTime timeEnded = DateTime.Now; log.Dispose(); return(new ScanResult(result, fileInfo.FullName, this, timeStarted, timeEnded, succeeded, exception)); }
public void then_child_properties_are_those_from_resolved_reference() { var generalCategory = LoggingSection .DescendentElements(x => x.ConfigurationType == typeof(TraceSourceData)) .Where(x => x.Name == "General").Single(); CollectionAssert.AreEquivalent(generalCategory.Properties.ToArray(), resolvedCategoryProperty.ChildProperties.ToArray()); }
protected override void Act() { logFilter = LoggingSection.GetDescendentsOfType <PriorityFilterData>().FirstOrDefault(); int maximumPriority = (int)logFilter.Property("MaximumPriority").Value; logFilter.Property("MinimumPriority").Value = maximumPriority + 1; logFilter.Validate(); }
internal void Configure(LoggingSection section) { if (section.ElementInformation.IsPresent) { LogTo = section.LogTo; LogResponses = section.LogResponses; LogMetrics = section.LogMetrics.GetValueOrDefault(false); } }
public void LoggingSection_CorrectNameShouldBeSetFromObject() { //Arrange LoggingSection loggingSection = new LoggingSection(this); //Act //Assert Assert.Equal("LoggingSectionTests", loggingSection.Name); }
public void LoggingSection_CorrectNameShouldBeSetFromString() { //Arrange LoggingSection loggingSection = new LoggingSection("Test"); //Act //Assert Assert.Equal("Test", loggingSection.Name); }
public void Disposed_ShouldBeFalseAfterConstruction() { //Arrange LoggingSection loggingSection = new LoggingSection(this); //Act //Assert Assert.False(loggingSection.Disposed); }
/// <summary> /// Refreshes configuration settings for the NlogLogger from the configuration file. /// </summary> public override void RefreshConfiguration() { try { base.RefreshConfiguration(); LoggingSection loggingSection = LoggingSection.GetSection(); LoggingSettingsElement loggingSettingsElement = loggingSection.LoggingSettings; _logFolder = loggingSettingsElement.LogFolder; _forwardToEventLogger = loggingSettingsElement.ForwardToEventLogger; // Set eventSources according to the configuration. _eventSources = new SortedList <int, EventRange>(); LoggingSourceCollection eventSourcesCollection = loggingSection.LoggingSettings.Sources; foreach (LoggingSourceElement eventSourceElement in eventSourcesCollection) { string source = eventSourceElement.Name; int min = 0; int max = 0; string ranges = eventSourceElement.Range; string[] rangeList = ranges.Split(','); foreach (string range in rangeList) { int pos = range.IndexOf('-'); if ((pos <= 0) || (pos >= range.Length - 1)) { throw new Exception("Invalid format for event range. Expected hyphen between min and max values."); } else { try { min = Int32.Parse(range.Substring(0, pos)); max = Int32.Parse(range.Substring(pos + 1)); } catch (Exception exception) { throw new Exception("Invalid format for event range. Could not parse min and max values.", exception); } EventRange eventRange = new EventRange(min, max, source); _eventSources.Add(min, eventRange); } } } // Set the eventIdFilter according to the configuration. _eventIdFilter = loggingSection.LoggingSettings.EventIdFilter; if (_eventIdFilter != null) { _eventIdFilter = "," + _eventIdFilter + ","; } } catch (Exception exception) { Logger.WriteWarning("The configuration for the NlogLogger could not be loaded from the application configuration file. Default values will be used.", 151); throw exception; } }
public void Disposed_ShouldBeTrueAfterDisposal() { //Arrange LoggingSection loggingSection = new LoggingSection(this); //Act loggingSection.Dispose(); //Assert Assert.True(loggingSection.Disposed); }
public void CreateChild_ParentShouldBeSetInChild() { //Arrange LoggingSection loggingSection = new LoggingSection(this); //Act LoggingSection child = new LoggingSection(this, loggingSection); //Assert Assert.Equal(loggingSection, child.Parent); }
public void GetChildren_ShouldReturnNullAfterDisposal() { //Arrange LoggingSection loggingSection = new LoggingSection(this); //Act loggingSection.Dispose(); //Assert Assert.Null(loggingSection.GetChildren()); }
public void LogMessages_ShouldBeEmptyAfterConstruction() { //Arrange LoggingSection loggingSection = new LoggingSection(this); //Act //Assert Assert.NotNull(loggingSection.GetLogMessages()); Assert.True(loggingSection.GetLogMessages().Count == 0); }
public void LoggingSection_CorrectNameShouldBeSetFromObjectWithGenericType() { //Arrange List <object> list = new List <object>(); LoggingSection loggingSection = new LoggingSection(list); //Act loggingSection.Info("Test"); //Assert Assert.Equal("List`1<Object>", loggingSection.Name); }
public void LogMessages_ShouldHaveOneEntryAfterLogging() { //Arrange LoggingSection loggingSection = new LoggingSection(this); //Act loggingSection.Info("Test"); //Assert Assert.NotNull(loggingSection.GetLogMessages()); Assert.True(loggingSection.GetLogMessages().Count == 1); }
internal void Configure(LoggingSection section) { LogTo = section.LogTo; LogResponses = section.LogResponses; LogMetrics = section.LogMetrics.GetValueOrDefault(false); LogMetricsFormat = section.LogMetricsFormat; if (section.LogMetricsCustomFormatter != null && typeof(IMetricsFormatter).IsAssignableFrom(section.LogMetricsCustomFormatter)) { LogMetricsCustomFormatter = Activator.CreateInstance(section.LogMetricsCustomFormatter) as IMetricsFormatter; } }
/// <summary> /// Creates an ILogger implementation. The instance is a singleton. /// </summary> /// <returns>A reference to the ILogger implementation.</returns> public static ILogger GetLogger() { string instanceName = ""; string className = ""; string assemblyName = ""; ILogger logger = null; try { lock (_lock) { if (_instance == null) { // Try to load the logging congiguration section. LoggingSection section = null; try { section = LoggingSection.GetSection(); } catch (Exception exception) { _instance = new NullLogger("NullLogger"); logger.WriteWarning("Logging is not configured. No logging will be performed.", 152); } // If the logging configuration section was loaded, try to load the logging provider. if (section != null) { try { ClassSpecificationElement spec = section.LoggingProvider; instanceName = spec.Name; className = spec.Class; assemblyName = spec.Assembly; _instance = (ILogger)Factory.CreateComponent(instanceName, className, assemblyName); _instance.RefreshConfiguration(); } catch (Exception exception) { _instance = new NullLogger("NullLogger"); logger.WriteError("Failed to create ILogger implementation. No logging will be performed.", 152); } } } logger = _instance; } } catch (Exception exception) { logger.WriteError("Failed to create ILogger implementation.: " + exception.ToString(), 152); throw exception; } return(logger); }
/// <summary> /// Logs the exception accordingly to the provided <paramref name="LoggingType"/> /// and <paramref name="ErrorSeverity"/>. If the <paramref name="ErrorSeverity"/> is /// <see cref="ErrorSeverity.Critical"/>, the error will always be logged using the /// logging type <see cref="LoggingType.EnterpriseLibrary"/>. /// </summary> /// <param name="Exception">The exception to log.</param> /// <param name="LoggingType">The type of logging to perform.</param> /// <param name="ErrorSeverity">The severity of the error.</param> public void Log(Exception Exception, LoggingType LoggingType = LoggingType.EnterpriseLibrary, ErrorSeverity ErrorSeverity = ErrorSeverity.Critical) { LoggingSection LoggingSection = null; try { LoggingSection = ConfigurationManager.GetSection("Logging") as LoggingSection; } catch (ConfigurationErrorsException) { LoggingSection = null; } bool UseLoggingConfig = (LoggingSection != null) ? LoggingSection.Logging.Count > 0 : false; // If the key in the web config doesn't exist, by default only log critical errors ErrorSeverity SeverityToLog = (LoggingSection == null) ? ErrorSeverity.Critical : (ErrorSeverity)LoggingSection.LoggingLevel; if (LoggingSection == null) { try { // try to use default value from web config string Severity = ConfigurationManager.AppSettings[DEFAULT_CONFIG_SEVERITY_TO_LOG]; // If the value in the web config is not null or empty.. if (!string.IsNullOrEmpty(Severity)) { // Try to parse it into an int. int num; if (int.TryParse(Severity, out num)) { SeverityToLog = (ErrorSeverity)num; // cast it as ErrorSeverity enumeration value } // NOTE: If the enumeration ErrorSeverity does not contain the value you are // trying to cast it as, it will simply stay as an int with that value (that's called magic). } } catch (ConfigurationErrorsException) { } } // Check web config (or default) value to see if we care about logging the error. if (SeverityToLog.HasFlag(ErrorSeverity)) { // Log the error using the Exception Policy described in the web config if (LoggingType.HasFlag(LoggingType.EnterpriseLibrary)) { WriteToEnterpriseLibraryFile(Exception, ErrorSeverity, UseLoggingConfig); } // Log the error using the text file path provided in the web config // NOTE: The message is prepended with the severity level for easy lookup if (LoggingType.HasFlag(LoggingType.TextFile)) { WriteToTextFile(ErrorSeverity.ToString().ToUpper() + ": " + Exception.Message, ErrorSeverity, UseLoggingConfig); } } }
protected override void Arrange() { base.Arrange(); StringBuilder xmlContents = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(xmlContents)) { LoggingSection.WriteXml(writer); } loggingSectionXml = XDocument.Parse(xmlContents.ToString()); }
public void Log_ReturnedLogMessage_ShouldHaveLogLevelVerbose() { //Arrange LoggingSection loggingSection = new LoggingSection(this); LogMessage logMessage; //Act logMessage = loggingSection.Verbose("Test"); //Assert Assert.NotNull(logMessage); Assert.Equal(LogLevel.VERBOSE, logMessage.LogLevel); }
public void Log_ReturnedLogMessage_ShouldHaveLogLevelWarning() { //Arrange LoggingSection loggingSection = new LoggingSection(this); LogMessage logMessage; //Act logMessage = loggingSection.Warning("Test"); //Assert Assert.NotNull(logMessage); Assert.Equal(LogLevel.WARNING, logMessage.LogLevel); }
public void Log_ReturnedLogMessage_ShouldHaveLogLevelError() { //Arrange LoggingSection loggingSection = new LoggingSection(this); LogMessage logMessage; //Act logMessage = loggingSection.Error("Test"); //Assert Assert.NotNull(logMessage); Assert.Equal(LogLevel.ERROR, logMessage.LogLevel); }
public void LogMessage_ShouldHaveCorrectLoggingSection() { //Arrange LoggingSection loggingSection = new LoggingSection(this); LogMessage logMessage; //Act logMessage = loggingSection.Log(LogLevel.INFO, "Test"); //Assert Assert.NotNull(logMessage); Assert.Equal(loggingSection, logMessage.LoggingSection); }
public void Log_ReturnedLogMessage_ShouldHaveLogLevelCritical() { //Arrange LoggingSection loggingSection = new LoggingSection(this); LogMessage logMessage; //Act logMessage = loggingSection.Critical("Test"); //Assert Assert.NotNull(logMessage); Assert.Equal(LogLevel.CRITICAL, logMessage.LogLevel); }
public void LogHandler_ShouldNotTriggerIfLogLevelDisabled() { //Arrange TestLogHandler testLogHandler = new TestLogHandler(new LogLevel[0]); Logger.LogHandlers += testLogHandler.OnLog; LoggingSection loggingSection = new LoggingSection(this); //Act loggingSection.Info("Test"); //Assert Assert.False(testLogHandler.Triggered); }
public void LogHandler_ShouldTriggerIfLogLevelEnabled() { //Arrange TestLogHandler testLogHandler = new TestLogHandler(new LogLevel[] { LogLevel.INFO }); Logger.LogHandlers += testLogHandler.OnLog; LoggingSection loggingSection = new LoggingSection(this); //Act loggingSection.Info("Test"); //Assert Assert.True(testLogHandler.Triggered); }
public void LogMessage_ShouldHaveCorrectMessage() { //Arrange LoggingSection loggingSection = new LoggingSection(this); LogMessage logMessage; string message = "Test"; //Act logMessage = loggingSection.Log(LogLevel.INFO, message); //Assert Assert.NotNull(logMessage); Assert.Equal(message, logMessage.Message); }
internal void Configure(LoggingSection section) { if (section != null) { LogTo = section.LogTo; LogResponses = section.LogResponses; LogMetrics = section.LogMetrics.GetValueOrDefault(false); LogMetricsFormat = section.LogMetricsFormat; LogResponsesSizeLimit = (section.LogResponsesSizeLimit.HasValue ? section.LogResponsesSizeLimit.Value : 1024); if (section.LogMetricsCustomFormatter != null && typeof(IMetricsFormatter).IsAssignableFrom(section.LogMetricsCustomFormatter)) { LogMetricsCustomFormatter = (Activator.CreateInstance(section.LogMetricsCustomFormatter) as IMetricsFormatter); } } }
public void CreateChild_ShouldAddChildToParentsChildrenList() { //Arrange LoggingSection loggingSection = new LoggingSection(this); //Act LoggingSection child1 = new LoggingSection(this, loggingSection); LoggingSection child2 = new LoggingSection(this, loggingSection); IReadOnlyCollection <LoggingSection> children = loggingSection.GetChildren(); //Assert Assert.Equal(2, children.Count); Assert.Contains(child1, children); Assert.Contains(child2, children); }
public Scanners() { logging = new LoggingSection(this); scanners = new List <Scanner>(); logging.Info("Initializing scanners"); foreach (Type type in AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => !p.IsInterface && p != typeof(Scanner) && typeof(Scanner).IsAssignableFrom(p)) .Where(t => t.GetConstructors().All(c => c.GetParameters().Length == 0))) { Scanner scanner = (Scanner)Activator.CreateInstance(type); logging.Debug($"Created instance of {type.Name}"); scanners.Add(scanner); } }
public static void Init() { Conf = new LoggingSection(); Config.AddSection("logging", Conf); }