public void Validate() { if (string.IsNullOrEmpty(Name)) { throw new ArgumentException("sessionName", "Session name can't be null"); } if (!RealTimeSession && string.IsNullOrEmpty(LogFilePath)) { throw new ArgumentException("logFilePath", "log file name must be specified for non-real time session"); } if (MinBuffers != 0 && MaxBuffers != 0 && MaxBuffers < MinBuffers) { throw new ArgumentException("maximumBuffers", "maximumBuffers must be greater than or equal to the value for minimumBuffers."); } if (UseNewFileMode) { if (MaxFileSize == 0) { throw new ArgumentException("maxFileSize", "maxFileSize must be specified if in NEWFILE mode"); } if (!LogFilePath.Contains("%d")) { throw new ArgumentException("logFilePath", "Must specify '%d' in the logFilePath if using NEWFILE mode"); } } }
public FileLog(IOptionsSource optionsSource) { if (optionsSource is null) { throw new ArgumentNullException(nameof(optionsSource)); } _path = optionsSource.LogOptions.LogFilePath; }
public void SetUp() { _currentDate = DateTime.Now.Date; _nextDayDate = _currentDate.AddDays(1); // Mock out the Date Time Provider _testDateTimeProvider = new Mock <IDateTimeProvider>(); _testDateTimeProvider.Setup(x => x.Now).Returns(_currentDate); _logPath = new LogFilePath(_testDateTimeProvider.Object, TEST_DIRECTORY, TEST_FILE_NAME, TEST_LOG_EXTENSION); }
public void FullFilePath_Rollover() { // Create a date time provider that will start off on the current day and simulate a rollover to the next day Mock <IDateTimeProvider> rolloverProvider; rolloverProvider = new Mock <IDateTimeProvider>(); rolloverProvider.SetupSequence(x => x.Now) .Returns(_currentDate.Date) .Returns(_nextDayDate.Date); _logPath = new LogFilePath(rolloverProvider.Object, TEST_DIRECTORY, TEST_FILE_NAME, TEST_LOG_EXTENSION); _logPath.CheckDate(); string expectedFormat = $"{TEST_DIRECTORY}{TEST_FILE_NAME}_{_nextDayDate.ToString(DATE_FORMAT)}.{TEST_LOG_EXTENSION}"; Assert.AreEqual(expectedFormat, _logPath.FullFilePath); }
public static IWebHost BuildWebHost(string[] args) { var webHostBuilder = WebHost.CreateDefaultBuilder(args) .UseStartup <Startup>() .UseSerilog((webHostContext, loggerConfiguration) => { loggerConfiguration.Enrich.WithThreadId(); var environment = webHostContext.HostingEnvironment; if (environment.IsDevelopment()) { loggerConfiguration.MinimumLevel.Debug(); loggerConfiguration.MinimumLevel .Override(ELogEventSource.System.ToString(), LogEventLevel.Warning); loggerConfiguration.MinimumLevel .Override(ELogEventSource.Microsoft.ToString(), LogEventLevel.Warning); } loggerConfiguration.MinimumLevel.Information(); loggerConfiguration.MinimumLevel .Override(ELogEventSource.System.ToString(), LogEventLevel.Error); loggerConfiguration.MinimumLevel .Override(ELogEventSource.Microsoft.ToString(), LogEventLevel.Error); loggerConfiguration.Enrich.FromLogContext(); if (environment.IsDevelopment()) { loggerConfiguration.WriteTo.Console(); } var logFilePath = string.Format(environment.ContentRootPath + LogFilePath.FormatPathSeparators(), environment.EnvironmentName); loggerConfiguration.WriteTo.File( path: logFilePath, outputTemplate: LogEntryTemplate.Replace("{0}", TimestampFormat), rollingInterval: RollingInterval.Day); }); var webHost = webHostBuilder.Build(); return(webHost); }
public virtual void Log(LogLevel logLevel, string msg, Exception ex = null) { try { // 输出日志 => 自定义(默认无) CustomOutputLog?.Invoke(this, new CustomOutputLogEventArgs(_options, logLevel, msg, ex)); if (!_options.LogToConsole && !_options.LogToLocalFile) { return; } string msgFormat; bool hasOutputConsole; if (MsgFormat != null) { var args = new MsgFormatEventArgs(_options, ClassType, logLevel, msg, ex); MsgFormat(this, args); msgFormat = args.MsgFormat; hasOutputConsole = args.HasOutputConsole; } else { msgFormat = DefaultHandleMsgFormat(ClassType, logLevel, msg, ex, out hasOutputConsole); } if (!string.IsNullOrWhiteSpace(msgFormat)) { if (!hasOutputConsole && _options.LogToConsole && logLevel >= _options.MinLogLevelForConsole) { // 输出日志 => 控制台 Console.WriteLine(msgFormat); } if (_options.LogToLocalFile && logLevel >= _options.MinLogLevelForLocalFile) { // 输出日志 => 本地文件 try { _locker.EnterWriteLock(); var filePath = LogFilePath?.Invoke(); if (string.IsNullOrWhiteSpace(filePath)) { throw new Exception("Log file path cannot be empty!"); } #region 日志文件备份 if (_options.MaxFileSize > 0 && File.Exists(filePath)) { //var msgByteCount = Options.DefaultEncoding.GetByteCount(msgFormat); var fileInfo = new FileInfo(filePath); if (fileInfo.Length >= _options.MaxFileSize) { var backupFilePath = PathHelper.GetBackupFilePath(filePath, out _); File.Move(filePath, backupFilePath); } } #endregion //using (var sw = File.AppendText(filePath)) using (var sw = new StreamWriter(filePath, true, DefaultEncoding)) { sw.WriteLine(msgFormat); sw.Close(); } } finally { if (_locker.IsWriteLockHeld) { _locker.ExitWriteLock(); } } } } } catch (Exception exception) { if (OnException != null) { OnException(this, new EventArgs <Exception>(exception)); } else { DefaultHandleInternalException(exception); } } }
/// <summary> /// Opens the logfile or creates a new one. /// </summary> public void OpenLogFile() { if (_writer != null) { return; } if (string.IsNullOrEmpty(LogFilePath)) { /* Different methods to get the directory of execution. * Console.WriteLine( Assembly.GetEntryAssembly().Location ); * Console.WriteLine( new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath ); * Console.WriteLine( Assembly.GetEntryAssembly().Location ); * Console.WriteLine( Environment.GetCommandLineArgs()[0] ); * Console.WriteLine( Process.GetCurrentProcess().MainModule.FileName ); */ //LogFilePath = System.Windows.Forms.Application.ExecutablePath + ".log"; LogFilePath = Environment.CurrentDirectory + ".log"; LogFilePath = LogFilePath.Replace(".exe", "").Replace(".EXE", ""); } if (string.IsNullOrEmpty(LogFilePath)) { throw (new Exception("Invalid or empty log file path given!!!")); } // Determine the log file name per its naming type: if (LogFileNameType == LogFileNamingType.Circular) { LogFilePath = GetCircularFileName(LogFilePath); // Determine if log file exists and needs to be overwritten: if (File.Exists(LogFilePath) == true) { TimeSpan tm = DateTime.Now - File.GetLastWriteTime(LogFilePath); if (tm.TotalDays >= 1) { AppendToFile = false; } } } else if (LogFileNameType == LogFileNamingType.DateStamped) { LogFilePath = GetDateStampedFileName(LogFilePath); } int retryWriteCount = 0; while (retryWriteCount <= 10) { try { _writer = new StreamWriter(LogFilePath, AppendToFile); retryWriteCount = 100; // Write was successful, don't retry. } catch (System.IO.IOException ex) { // If the log is being viewed from a remote server using EditPlus or any other text-editing software that refreshes // constantly, this error will come up: if (Regex.IsMatch(ex.Message, "The process cannot access the file .* because it is being used by another process", RegexOptions.IgnoreCase)) { // Sleep 500 ms and try again: retryWriteCount++; System.Threading.Thread.Sleep(1000); } else { throw (ex); } } } } // END FUNCTION
/// <summary> /// Constructor /// </summary> /// <param name="configFile">The path to the logging configuration file</param> /// <param name="generator">The generator to use for log messages</param> /// <param name="fileExtension">The extension for the log file</param> public FileLogger(string configFile, ILogMessageGenerator generator, string fileExtension) : base(configFile) { _messageGenerator = generator; _logFilePath = new LogFilePath(Configuration.LogDirectory, Configuration.BaseFileName, fileExtension); }
public static void SetLogFilePath(LogFilePath logFilePath) { Logger.logFilePath = logFilePath; }