public void logCNC() { String filename = LoggerSettings.Instance().logFiledir + LoggerSettings.Instance().logFilename; using (StreamWriter file = new StreamWriter(@filename)) { LogEvent e = LoggerManager.THE().getCurrentLogEvent(); string[] keys = LoggerManager.THE().getAllKeys(); if (writeTitle) { String lineTitle = ""; foreach (string k in keys) { if (LoggerManager.THE().getBoolLogKey(k)) { lineTitle += e.getLoggableName(k) + ";"; } //lineTitle += LoggerManager.THE().getDataNameByKey(k) + ";"; } lineTitle += "Datum;"; lineTitle += "Uhrzeit;"; file.WriteLine(lineTitle); } while (LoggerSettings.Instance().logThreadRunning) { String line = ""; foreach (string k in keys) { if (LoggerManager.THE().getBoolLogKey(k)) { line += e.getLoggableValue(k) + ";"; } //line += e.getValueByKey(k) + ";"; } line += DateTime.Now.ToString("dd-MM-yyyy") + ";"; //23 line += DateTime.Now.ToString("HH:mm:ss.ff"); //24 file.WriteLine(line); LoggerSettings.Instance().loggedEntriesCount += 1; System.Threading.Thread.Sleep(LoggerSettings.Instance().logInterval); } } }
public void TestBaseLoggable_Constructor_Default() { TestLoggerFactory.Should().NotBeNull("initialized in constructor"); LoggerSettings.Should().NotBeNull("initialized in constructor"); Logger.Should().NotBeNull("initialized in constructor"); TestOutputHelper.Should().NotBeNull("initialized in constructor"); }
private IEnumerable <LoggingEvent> GetFilteredEvents(LoggerSettings loggerSetting) { if (_memoryAppender == null) { return(Enumerable.Empty <LoggingEvent>()); } IEnumerable <LoggingEvent> res = _memoryAppender.GetEvents().Distinct().Where(l => l.Level >= loggerSetting.Level).OrderBy(l => l.TimeStamp); if (res.Any() && !string.IsNullOrEmpty(loggerSetting.LoggerName)) { res = res.Where(l => l.LoggerName.Contains(loggerSetting.LoggerName)); } if (res.Any() && !string.IsNullOrEmpty(loggerSetting.ThreadName)) { res = res.Where(l => l.ThreadName == loggerSetting.ThreadName); } if (res.Any() && !string.IsNullOrEmpty(loggerSetting.UserName)) { res = res.Where(l => l.UserName == loggerSetting.UserName); } if (res.Any()) { res = res.Where(l => ((l.TimeStamp.Ticks >= loggerSetting.StartDate.Ticks) && (l.TimeStamp.Ticks <= loggerSetting.EndDate.Ticks))); } return(res); }
protected virtual void Dispose(bool Disposing) { if (_disposed) { return; } while ((_traceQueue?.Count > 0) || (_performanceQueue?.Count > 0) || (_metricQueue?.Count > 0)) { Thread.Sleep(_queueIntervalMsec); // Wait for queues to drain. } if (Disposing) { // Free managed objects. _settings = null; _exeLocation = null; _criticalErrorFilename = null; _tasks = null; } // Free unmanaged objects. _timer?.Dispose(); _timer = null; _traceQueue?.Dispose(); _traceQueue = null; _performanceQueue?.Dispose(); _performanceQueue = null; _metricQueue?.Dispose(); _metricQueue = null; _disposed = true; }
/// <summary> /// </summary> /// <param name="factory">The <see cref="ILoggerFactory" /> to use.</param> /// <param name="configuration">The <see cref="IConfiguration" /> to use for <see cref="ILoggerSettings" />.</param> /// <param name="logService"></param> /// <returns></returns> public static ILoggerFactory AddLog(this ILoggerFactory factory, IConfiguration configuration, ILogService logService) { var settings = new LoggerSettings(configuration); return(factory.AddLog(settings, logService)); }
public PeerCastStationSettings() { Logger = new LoggerSettings(); Listeners = new ListenerSettings[0]; AccessController = new AccessControllerSettings(); YellowPages = new YellowPageSettings[0]; }
private static void Loggers() { var settings = new LoggerSettings { FormatJson = false }; var logger = LogManager.GetClassLogger(settings); logger.Info("IEnumerable formatting test:"); for (var i = 0; i < 5; i++) { var list = new List <string> { "cool string" + i, "another cool string" }; var dict = new Dictionary <string, bool> { { "Go to the party?" + i, true }, { "Go to the school?", false } }; var set = new HashSet <string> { "cool string" + i, "another cool string" }; logger.Info(list, dict, set); } }
protected ConcurrentLoggerBase(LoggerSettings Settings) { _settings = Settings; _exeLocation = Assembly.GetEntryAssembly()?.Location ?? Assembly.GetExecutingAssembly().Location; _criticalErrorFilename = Path.Combine(Path.GetDirectoryName(_exeLocation) ?? @"C:\", $"{Path.GetFileNameWithoutExtension(_exeLocation)}.log"); // Create queues. var queues = 0; if (Settings.TraceLogLevel != LogLevel.None) { _traceQueue = new BlockingCollection <TraceLog>(new ConcurrentQueue <TraceLog>()); queues++; } if (Settings.EnablePerformanceLog) { _performanceQueue = new BlockingCollection <PerformanceLog>(new ConcurrentQueue <PerformanceLog>()); queues++; } if (Settings.EnableMetricLog) { _metricQueue = new BlockingCollection <MetricLog>(new ConcurrentQueue <MetricLog>()); queues++; } if (queues > 0) { // Cannot await tasks because constructor cannot be marked async. Create timer instead. // Timer calls method on a ThreadPool thread. _tasks = new List <Task>(queues); _timer = new Timer(WriteLogs, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(_queueIntervalMsec)); } }
public LoggerMiddleware(LoggerSettings settings, RequestDelegate next, ICustomLoggerFactory customLoggerFactory) { _next = next ?? throw new ArgumentNullException(nameof(next)); _settings = settings; _customLoggerFactory = customLoggerFactory; }
public CustomLogger(string name, IServiceProvider serviceProvider, LoggerSettings loggerSettings, IAsyncLoggerProcessor asyncLoggerProcessor) { Name = name; ServiceProvider = serviceProvider; Settings = loggerSettings; LoggerProcessor = asyncLoggerProcessor; }
/// <summary> /// Add console logger in runsettings if exists. /// </summary> /// <param name="document">Runsettings document.</param> /// <param name="loggerRunSettings">Logger run settings.</param> /// <returns>True if updated console logger in runsettings successfully.</returns> private bool UpdateConsoleLoggerIfExists( XmlDocument document, LoggerRunSettings loggerRunSettings) { var defaultConsoleLogger = new LoggerSettings { FriendlyName = ConsoleLogger.FriendlyName, Uri = new Uri(ConsoleLogger.ExtensionUri) }; var existingLoggerIndex = loggerRunSettings.GetExistingLoggerIndex(defaultConsoleLogger); // Update assemblyQualifiedName and codeBase of existing logger. if (existingLoggerIndex >= 0) { var consoleLogger = loggerRunSettings.LoggerSettingsList[existingLoggerIndex]; consoleLogger.AssemblyQualifiedName = typeof(ConsoleLogger).AssemblyQualifiedName; consoleLogger.CodeBase = typeof(ConsoleLogger).GetTypeInfo().Assembly.Location; RunSettingsProviderExtensions.UpdateRunSettingsXmlDocumentInnerXml( document, Constants.LoggerRunSettingsName, loggerRunSettings.ToXml().InnerXml); return(true); } return(false); }
private void timer_Tick(object sender, EventArgs e) { SuspendLayout(); LoggerManager.THE().readFromCNC(); LogEvent ev = LoggerManager.THE().getCurrentLogEvent(); foreach (Label l in dataLabels) { l.Text = ev.getValueByKey(l.Tag.ToString()); } while (LoggerManager.THE().logsQueued()) { lb_LogOutput.Items.Add(LoggerManager.THE().popLog()); } val_localIP.Text = Utils.GetLocalIPAddress(); val_extIP.Text = Utils.GetGlobalIPAddress(); //File Logger Tab val_lblUsedInterval.Text = LoggerSettings.Instance().logInterval.ToString(); lblLogCount.Text = LoggerSettings.Instance().loggedEntriesCount.ToString(); ResumeLayout(); }
public LoggerDlg() { InitializeComponent(); LoggerSettings.Instance().logInterval = Convert.ToInt32(numLogInterval.Value); tableData.CellBorderStyle = TableLayoutPanelCellBorderStyle.Outset; tableData.AutoSize = true; tableData.AutoSizeMode = AutoSizeMode.GrowOnly; TableLayoutRowStyleCollection styles = tableData.RowStyles; foreach (RowStyle style in styles) { style.SizeType = SizeType.Absolute; style.Height = 20; } string[] keys = LoggerManager.THE().getAllKeys(); for (int i = 0; i < keys.Length; i++) { LoggerManager.THE().addLog("added key: " + keys[i]); Label l = createLabel(keys[i]); dataLabels.Add(l); tableData.Controls.Add(createLabel(keys[i]), 0, i); tableData.Controls.Add(l, 1, i); CheckBox c = createCheckbox(keys[i]); dataCheckboxes.Add(c); tableData.Controls.Add(c, 2, i); } timer.Start(); }
/// <summary> /// Конструктор класса /// </summary> /// <param name="logFilename"></param> public Logger(string logFilename = null) { Settings = new LoggerSettings(); Settings.LogFilename = logFilename; if (logFilename == null) { Settings.WriteToFile = false; } }
internal static ISettings GetSettings(IConfiguration configuration) { string sourceRoot = configuration.GetValue <string>("SourceRoot"); string destinationRootUrl = configuration.GetValue <string>("DestinationRootUrl"); string destinationRootPath = configuration.GetValue <string>("DestinationRootPath"); ILocation destinationRoot = new Location(new Uri(destinationRootUrl), destinationRootPath); IConfigurationSection rateLimiterConfig = configuration.GetSection("RateLimiter"); IRateLimiterSettings rateLimiterSettings = new RateLimiterSettings { Enabled = rateLimiterConfig.GetValue("Enabled", false), TimeWindowInMinutes = rateLimiterConfig.GetValue("TimeWindowInMinutes", 10), MaxRequestsInTimeWindow = rateLimiterConfig.GetValue("MaxRequestsInTimeWindow", 100), MaxBytesInTimeWindow = rateLimiterConfig.GetValue("MaxBytesInTimeWindow", 1024 * 1024 * 50), Whitelist = rateLimiterConfig.GetSection("Whitelist").GetChildren().ToList().Select(x => x.Value).ToArray(), Blacklist = rateLimiterConfig.GetSection("Blacklist").GetChildren().ToList().Select(x => x.Value).ToArray() }; IConfigurationSection loggerConfig = configuration.GetSection("Logger"); ILoggerSettings loggerSettings = new LoggerSettings { WriteInfo = loggerConfig.GetValue("WriteInfo", false), WriteWarnings = loggerConfig.GetValue("WriteWarnings", false), WriteErrors = loggerConfig.GetValue("WriteErrors", false), ToConsole = loggerConfig.GetValue("ToConsole", false), ToFile = loggerConfig.GetValue("ToFile", false), Directory = loggerConfig.GetValue("Directory", string.Empty) }; IConfigurationSection gifConfig = configuration.GetSection("GifSettings"); IGifSettings gifSettings = new GifSettings { PostProcessorEnabled = gifConfig.GetValue("PostProcessorEnabled", false), PostProcessorCommand = gifConfig.GetValue("PostProcessorCommand", string.Empty) }; IConfigurationSection jpegConfig = configuration.GetSection("JpegSettings"); IJpegSettings jpegSettings = new JpegSettings { Quality = jpegConfig.GetValue("Quality", 75), PostProcessorEnabled = jpegConfig.GetValue("PostProcessorEnabled", false), PostProcessorCommand = jpegConfig.GetValue("PostProcessorCommand", string.Empty) }; IConfigurationSection pngConfig = configuration.GetSection("PngSettings"); IPngSettings pngSettings = new PngSettings { CompressionLevel = pngConfig.GetValue("CompressionLevel", 6), PostProcessorEnabled = pngConfig.GetValue("PostProcessorEnabled", false), PostProcessorCommand = pngConfig.GetValue("PostProcessorCommand", string.Empty) }; Settings settings = new Settings(sourceRoot, destinationRoot, rateLimiterSettings, loggerSettings, gifSettings, jpegSettings, pngSettings); return(settings); }
public ActionResult Filter(LoggerSettings loggerSetting) { LogSettingAndEvents logSettingAndEvents = new LogSettingAndEvents(); logSettingAndEvents.IsStarted = _memoryAppender != null ? _memoryAppender.IsStarted : false; logSettingAndEvents.LoggingEvents = GetFilteredEvents(loggerSetting); logSettingAndEvents.LoggerSetting = loggerSetting; return(View("Show", logSettingAndEvents)); }
private void btnOutputFolder_Click(object sender, EventArgs e) { if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { LoggerSettings.Instance().logFiledir = folderBrowserDialog1.SelectedPath + "\\"; val_lblOutputFolder.Text = LoggerSettings.Instance().logFiledir; btnStartStopLogging.Enabled = true; } }
//Service collection public static IServiceCollection AddFileLogger(this IServiceCollection services, IConfiguration loggerSettings) { services = services ?? throw new ArgumentNullException(nameof(services)); loggerSettings = loggerSettings ?? throw new ArgumentNullException(nameof(loggerSettings)); var settings = new LoggerSettings(loggerSettings); services.AddFileLogger(settings); return(services); }
private void btnFilename_Click(object sender, EventArgs e) { String value = LoggerSettings.Instance().logFilename; if (InputBox("Output Datei Name", "Änder Sie hier den Dateiname:", ref value) == DialogResult.OK) { LoggerSettings.Instance().logFilename = value; val_lblFilename.Text = LoggerSettings.Instance().logFilename; } }
public static void DbInvoke(LoggerSettings settings, Exception exception, string messageTemplate, int logLevel, params object[] propertyValues) { Logger logger = DbLog(settings, logLevel); switch (logLevel) { case (int)LogEventLevel.Debug: logger.Debug(messageTemplate, propertyValues); break; case (int)LogEventLevel.Fatal: logger.Fatal(messageTemplate, propertyValues); break; case (int)LogEventLevel.Verbose: logger.Verbose(messageTemplate, propertyValues); break; case (int)LogEventLevel.Error: logger.Error(messageTemplate, propertyValues); break; case (int)LogEventLevel.Information: logger.Information(messageTemplate, propertyValues); break; case (int)LogEventLevel.Warning: logger.Warning(messageTemplate, propertyValues); break; case (int)Enum.LogLevel.DebugModeError: logger.Debug(exception, messageTemplate, propertyValues); break; case (int)Enum.LogLevel.InformationModeError: logger.Information(exception, messageTemplate, propertyValues); break; case (int)Enum.LogLevel.VerboseModeError: logger.Verbose(exception, messageTemplate, propertyValues); break; case (int)Enum.LogLevel.FatalModeError: logger.Fatal(exception, messageTemplate, propertyValues); break; case (int)Enum.LogLevel.WarningModeError: logger.Warning(exception, messageTemplate, propertyValues); break; default: break; } }
public ActionResult Filter(LoggerSettings loggerSetting) { var logSettingAndEvents = new LogSettingAndEvents { IsStarted = _memoryAppender?.IsStarted ?? false, LoggingEvents = GetFilteredEvents(loggerSetting), LoggerSetting = loggerSetting }; return(View("Show", logSettingAndEvents)); }
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void ValidateSettings(LoggerSettings settings) { if (settings == null) { throw new Exception("LoggerSettings parameter cannot be null"); } if (string.IsNullOrWhiteSpace(settings.LogFileLocation)) { throw new Exception("LogFileLocation cannot be empty"); } }
public DbLoggerProcessor(LoggerSettings loggerSettings) : base(loggerSettings, new BlockingCollection <LogData>(new ConcurrentQueue <LogData>())) { var connString = Settings.ConnectionString; if (string.IsNullOrWhiteSpace(connString)) { throw new InvalidOperationException("Connection string missing or not supported"); } currentBatch = new List <LogData>(); maxQueueSize = Settings.DbBatchSize > 0 ? Settings.DbBatchSize : 100; }
public static (AppSettings appSettings, LoggerSettings loggerSettings) GetSettings() { var configuration = Build(); var appSettings = new AppSettings(); var loggerSettings = new LoggerSettings(); configuration.GetSection("AppSettings").Bind(appSettings); configuration.GetSection("Logging").Bind(loggerSettings); return(appSettings, loggerSettings); }
public static IServiceCollection AddDatabaseLogger(this IServiceCollection services, IConfiguration loggerSettings, IConfiguration connectionStrings) { services = services ?? throw new ArgumentNullException(nameof(services)); loggerSettings = loggerSettings ?? throw new ArgumentNullException(nameof(loggerSettings)); connectionStrings = connectionStrings ?? throw new ArgumentNullException(nameof(connectionStrings)); var settings = new LoggerSettings(loggerSettings, connectionStrings); services.AddDatabaseLoggerRequiredServices(settings); return(services); }
public void PureLogger_PushLogProperties() { var testLoggable = CreateTestLoggable(); using (TestCorrelator.CreateContext()) using (testLoggable.PushLogProperties(LoggerSettings.GetLogLevel(LoggingOutputFlags.TestCorrelator), LoggableFormat.ToLogWithParents)) { Logger.LogDebug(TestLogMsg); ValidateTestLog(LogLevel.Debug, LoggableFormat.ToLogWithParents); } }
static void LogVerboseException(HttpContext httpContext, Exception ex, LoggerSettings settings) { LogForErrorContext(httpContext) .Error(ex, settings.VerboseMessageTemplate, ex.Message, (int)CustomErrorCodes.Code.VerboseErrorCode); if (settings.IsSqlServerLog) { MSSqlDbLog.Invoke(settings, httpContext, ex, settings.VerboseMessageTemplate, ex.Message, 0, (int)LogEventLevel.Verbose); } ResponseWriteAsync(httpContext, ex, (int)CustomErrorCodes.Code.VerboseErrorCode); }
private void FormatRequest(HttpContext httpContext, Stopwatch sw, ILogger logger, LoggerSettings appSettings, MemoryStream injectedRequestStream) { string bodyAsText; using (var bodyReader = new StreamReader(httpContext.Request.Body)) { bodyAsText = bodyReader.ReadToEnd(); var bytesToWrite = System.Text.Encoding.UTF8.GetBytes(bodyAsText); injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length); injectedRequestStream.Seek(0, SeekOrigin.Begin); httpContext.Request.Body = injectedRequestStream; } if (!string.IsNullOrEmpty(bodyAsText)) { _customLoggerFactory.Debug(_settings.MessageTemplateForPostRequest, httpContext.Request.Path, httpContext.Request.Method, bodyAsText, sw.Elapsed.TotalMilliseconds); if (_settings.IsSqlServerLog) { MSSqlDbLog.Invoke(_settings, httpContext, null, _settings.MessageTemplateForPostRequest, bodyAsText, sw.Elapsed.TotalMilliseconds, (int)Enum.LogLevel.DebugModeRequest); } } else { _customLoggerFactory.Debug(_settings.MessageTemplateForGetRequest, httpContext.Request.Path, httpContext.Request.Method, sw.Elapsed.TotalMilliseconds); if (_settings.IsSqlServerLog) { MSSqlDbLog.Invoke(appSettings, httpContext, null, _settings.MessageTemplateForGetRequest, httpContext.Request.QueryString.Value, sw.Elapsed.TotalMilliseconds, (int)Enum.LogLevel.DebugModeRequest); } } }
private static Serilog.ILogger DevelopmentLogging <TImplementingType>(LoggerSettings loggerSettings) { return(new LoggerConfiguration() .WriteTo.File(loggerSettings.LogFileLocation, rollingInterval: RollingInterval.Day, retainedFileCountLimit: null, shared: true) .MinimumLevel.Is(MapLogEventLevel(loggerSettings.LogEventLevel)) .Enrich.FromLogContext() .WriteTo.Seq(loggerSettings.SeqUrl) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System", LogEventLevel.Warning) .CreateLogger() .ForContext(typeof(TImplementingType))); }
public void PureLoggable_PushLogProperties_PureLogLevel_Null() { Func <IDisposable> fx = () => ((IPureLoggable)null).PushLogProperties(LoggerSettings.GetLogLevel(LoggingOutputFlags.TestCorrelator)); fx.Should().Throw <ArgumentNullException>().And.ParamName.Should().Be("loggable"); var testLoggable = CreateTestLoggable(); fx = () => testLoggable.PushLogProperties(null); fx.Should().Throw <ArgumentNullException>().And.ParamName.Should().Be("pureLogLevel"); }