public RollingFileSink(string path,
                               ITextFormatter textFormatter,
                               long?fileSizeLimitBytes,
                               int?retainedFileCountLimit,
                               Encoding encoding,
                               bool buffered,
                               bool shared,
                               RollingInterval rollingInterval,
                               bool rollOnFileSizeLimit)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0)
            {
                throw new ArgumentException("Negative value provided; file size limit must be non-negative");
            }
            if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1)
            {
                throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1");
            }

            _roller                 = new PathRoller(path, rollingInterval);
            _textFormatter          = textFormatter;
            _fileSizeLimitBytes     = fileSizeLimitBytes;
            _retainedFileCountLimit = retainedFileCountLimit;
            _encoding               = encoding;
            _buffered               = buffered;
            _shared                 = shared;
            _rollOnFileSizeLimit    = rollOnFileSizeLimit;
        }
        public PathRoller(string path, RollingInterval interval)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            _interval     = interval;
            _periodFormat = interval.GetFormat();

            var pathDirectory = Path.GetDirectoryName(path);

            if (string.IsNullOrEmpty(pathDirectory))
            {
                pathDirectory = Directory.GetCurrentDirectory();
            }

            _directory       = Path.GetFullPath(pathDirectory);
            _filenamePrefix  = Path.GetFileNameWithoutExtension(path);
            _filenameSuffix  = Path.GetExtension(path);
            _filenameMatcher = new Regex(
                "^" +
                Regex.Escape(_filenamePrefix) +
                "(?<" + PeriodMatchGroup + ">\\d{" + _periodFormat.Length + "})" +
                "(?<" + SequenceNumberMatchGroup + ">_[0-9]{3,}){0,1}" +
                Regex.Escape(_filenameSuffix) +
                "$");

            DirectorySearchPattern = $"{_filenamePrefix}*{_filenameSuffix}";
        }
Beispiel #3
0
 /// <summary>Use Serilog as the logger.
 /// </summary>
 /// <returns></returns>
 public static Configuration UseSerilog(this Configuration configuration,
                                        string defaultLoggerName                  = "default",
                                        string defaultLoggerFileName              = "default",
                                        string defaultLoggerFileExtensions        = "-.log",
                                        string contextPropertyName                = "logger",
                                        string defaultLoggerConsoleOutputTemplate =
                                        "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] - {Message:lj}{NewLine}{Exception}",
                                        string defaultLoggerFileOutputTemplate =
                                        "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{logger}] - {Message:lj}{NewLine}{Exception}",
                                        bool defaultLoggerFileBuffered                   = true,
                                        long?defaultLoggerFileSizeLimitBytes             = null,
                                        RollingInterval defaultLoggerFileRollingInterval = RollingInterval.Day,
                                        bool defaultLoggerFileRollOnFileSizeLimit        = true,
                                        int?defaultLoggerFileRetainedFileCountLimit      = null,
                                        int?defaultLoggerFileFlushToDiskIntervalSenconds = 1,
                                        LogEventLevel consoleMinimumLevel                = LogEventLevel.Information,
                                        LogEventLevel fileMinimumLevel                   = LogEventLevel.Information)
 {
     return(UseSerilog(configuration, new SerilogLoggerFactory(
                           defaultLoggerName,
                           defaultLoggerFileName,
                           defaultLoggerFileExtensions,
                           contextPropertyName,
                           defaultLoggerConsoleOutputTemplate,
                           defaultLoggerFileOutputTemplate,
                           defaultLoggerFileBuffered,
                           defaultLoggerFileSizeLimitBytes,
                           defaultLoggerFileRollingInterval,
                           defaultLoggerFileRollOnFileSizeLimit,
                           defaultLoggerFileRetainedFileCountLimit,
                           defaultLoggerFileFlushToDiskIntervalSenconds,
                           consoleMinimumLevel,
                           fileMinimumLevel)));
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="filePath">Absolute or relative path to the log file.</param>
 /// <param name="rollingInterval">Interval, after which the logs will be rotated.</param>
 /// <param name="innerLogger">Inner logger that will possibly log to some other place.</param>
 public FileLogger(string filePath, RollingInterval rollingInterval, LoggerBase innerLogger = null) : base(innerLogger)
 {
     _logger = new LoggerConfiguration()
               .MinimumLevel.Debug()
               .WriteTo.File(filePath, rollingInterval: rollingInterval)
               .CreateLogger();
 }
Beispiel #5
0
        public static LoggerConfiguration ConfigueRollingFile(this LoggerSinkConfiguration configuration,
                                                              ITextFormatter formatter,
                                                              bool shared   = true,
                                                              bool buffered = false,
                                                              int retainedFileCountLimit             = 31,
                                                              int fileSizeLimitBytes                 = 1073741824,
                                                              LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
                                                              string path = null,
                                                              RollingInterval rollingInterval = RollingInterval.Day)
        {
            return(configuration.File(formatter,
                                      path ?? Path.Combine(
#if NETFULL
                                          AppDomain.CurrentDomain.BaseDirectory
#else
                                          AppContext.BaseDirectory
#endif
                                          , "logs", "log.log"),
                                      restrictedToMinimumLevel: restrictedToMinimumLevel,
                                      fileSizeLimitBytes: fileSizeLimitBytes,
                                      retainedFileCountLimit: retainedFileCountLimit,
                                      shared: shared,
                                      buffered: buffered,
                                      rollOnFileSizeLimit: true,
                                      rollingInterval: rollingInterval
                                      ));
        }
Beispiel #6
0
        public static DateTime?GetCurrentCheckpoint(this RollingInterval interval, DateTime instant)
        {
            switch (interval)
            {
            case RollingInterval.Infinite:
                return(null);

            case RollingInterval.Year:
                return(new DateTime(instant.Year, 1, 1, 0, 0, 0, instant.Kind));

            case RollingInterval.Month:
                return(new DateTime(instant.Year, instant.Month, 1, 0, 0, 0, instant.Kind));

            case RollingInterval.Day:
                return(new DateTime(instant.Year, instant.Month, instant.Day, 0, 0, 0, instant.Kind));

            case RollingInterval.Hour:
                return(new DateTime(instant.Year, instant.Month, instant.Day, instant.Hour, 0, 0, instant.Kind));

            case RollingInterval.Minute:
                return(new DateTime(instant.Year, instant.Month, instant.Day, instant.Hour, instant.Minute, 0, instant.Kind));

            default:
                throw new ArgumentException("Invalid rolling interval");
            }
        }
Beispiel #7
0
        /// <summary>
        /// Write log events to the specified file.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="formatter">A formatter, such as <see cref="JsonFormatter"/>, to convert the log events into
        /// text for the file. If control of regular text formatting is required, use the other
        /// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?, RollingInterval, bool, int?, Encoding, FileLifecycleHooks)"/>
        /// and specify the outputTemplate parameter instead.
        /// </param>
        /// <param name="path">Path to the file.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow.
        /// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit
        /// will be written in full even if it exceeds the limit.</param>
        /// <param name="buffered">Indicates if flushing to the output file can be buffered or not. The default
        /// is false.</param>
        /// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param>
        /// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param>
        /// <param name="rollingInterval">The interval at which logging will roll over to a new file.</param>
        /// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames
        /// will have a number appended in the format <code>_NNN</code>, with the first filename given no number.</param>
        /// <param name="retainedFileCountLimit">The maximum number of log files that will be retained,
        /// including the current log file. For unlimited retention, pass null. The default is 31.</param>
        /// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param>
        /// <param name="hooks">Optionally enables hooking into log file lifecycle events.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public static LoggerConfiguration File(
            this LoggerSinkConfiguration sinkConfiguration,
            ITextFormatter formatter,
            string path,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            long?fileSizeLimitBytes        = DefaultFileSizeLimitBytes,
            LoggingLevelSwitch levelSwitch = null,
            bool buffered = false,
            bool shared   = false,
            TimeSpan?flushToDiskInterval    = null,
            RollingInterval rollingInterval = RollingInterval.Infinite,
            bool rollOnFileSizeLimit        = false,
            int?retainedFileCountLimit      = DefaultRetainedFileCountLimit,
            Encoding encoding        = null,
            FileLifecycleHooks hooks = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            return(ConfigureFile(sinkConfiguration.Sink, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch,
                                 buffered, false, shared, flushToDiskInterval, encoding, rollingInterval, rollOnFileSizeLimit,
                                 retainedFileCountLimit, hooks));
        }
        /// <summary>
        /// Gets the next check point as <see cref="DateTime"/>.
        /// </summary>
        /// <param name="interval">The interval.</param>
        /// <param name="dateTime">The date time.</param>
        /// <returns>The next check point as <see cref="DateTime"/>.</returns>
        public static DateTime?GetNextCheckpoint(this RollingInterval interval, DateTime dateTime)
        {
            var current = GetCurrentCheckpoint(interval, dateTime);

            if (current is null)
            {
                return(null);
            }

            // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault
            switch (interval)
            {
            case RollingInterval.Year:
                return(current.Value.AddYears(1));

            case RollingInterval.Month:
                return(current.Value.AddMonths(1));

            case RollingInterval.Day:
                return(current.Value.AddDays(1));

            case RollingInterval.Hour:
                return(current.Value.AddHours(1));

            case RollingInterval.Minute:
                return(current.Value.AddMinutes(5));

            default:
                throw new ArgumentException("Invalid rolling interval");
            }
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="AmazonS3Sink" /> class.
        /// </summary>
        /// <param name="formatter">The formatter.</param>
        /// <param name="path">The path.</param>
        /// <param name="fileSizeLimitBytes">The file size limit bytes.</param>
        /// <param name="buffered">if set to <c>true</c> [buffered].</param>
        /// <param name="encoding">The encoding.</param>
        /// <param name="rollingInterval">The rolling interval.</param>
        /// <param name="retainedFileCountLimit">The retained file count limit.</param>
        /// <param name="hooks">The hooks.</param>
        /// <param name="bucketName">The Amazon S3 bucket name.</param>
        /// <param name="endpoint">The Amazon S3 endpoint.</param>
        /// <param name="awsAccessKeyId">The Amazon S3 access key id.</param>
        /// <param name="awsSecretAccessKey">The Amazon S3 secret access key.</param>
        /// <returns>A <see cref="LoggerConfiguration" /> to use with Serilog.</returns>
        /// <exception cref="ArgumentNullException">
        ///     addSink
        ///     or
        ///     formatter
        ///     or
        ///     path
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     Negative value provided; file size limit must be non-negative. - fileSizeLimitBytes
        ///     or
        ///     At least one file must be retained. - retainedFileCountLimit
        ///     or
        ///     Buffered writes are not available when file sharing is enabled. - buffered
        ///     or
        ///     File lifecycle hooks are not currently supported for shared log files. - hooks
        /// </exception>
        public AmazonS3Sink(
            ITextFormatter formatter,
            string path,
            long?fileSizeLimitBytes,
            bool buffered,
            Encoding encoding,
            RollingInterval rollingInterval,
            int?retainedFileCountLimit,
            FileLifecycleHooks hooks,
            string bucketName,
            RegionEndpoint endpoint,
            string awsAccessKeyId,
            string awsSecretAccessKey)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (string.IsNullOrWhiteSpace(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }

            if (string.IsNullOrWhiteSpace(awsAccessKeyId))
            {
                throw new ArgumentNullException(nameof(awsAccessKeyId));
            }

            if (string.IsNullOrWhiteSpace(awsSecretAccessKey))
            {
                throw new ArgumentNullException(nameof(awsSecretAccessKey));
            }

            if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0)
            {
                throw new ArgumentException("Negative value provided; file size limit must be non-negative.");
            }

            if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1)
            {
                throw new ArgumentException(
                          "Zero or negative value provided; retained file count limit must be at least 1.");
            }

            this.sink = new RollingFileSink(
                path,
                formatter,
                fileSizeLimitBytes,
                retainedFileCountLimit,
                encoding,
                buffered,
                rollingInterval,
                true,
                hooks,
                bucketName,
                endpoint,
                awsAccessKeyId,
                awsSecretAccessKey);
        }
Beispiel #10
0
        public static string GetFormat(this RollingInterval interval)
        {
            switch (interval)
            {
            case RollingInterval.Infinite:
                return("");

            case RollingInterval.Year:
                return("yyyy");

            case RollingInterval.Month:
                return("yyyyMM");

            case RollingInterval.Day:
                return("yyyyMMdd");

            case RollingInterval.Hour:
                return("yyyyMMddHH");

            case RollingInterval.Minute:
                return("yyyyMMddHHmm");

            default:
                throw new ArgumentException("Invalid rolling interval");
            }
        }
Beispiel #11
0
        public static DateTime?GetNextCheckpoint(this RollingInterval interval, DateTime instant)
        {
            var current = GetCurrentCheckpoint(interval, instant);

            if (current == null)
            {
                return(null);
            }

            switch (interval)
            {
            case RollingInterval.Year:
                return(current.Value.AddYears(1));

            case RollingInterval.Month:
                return(current.Value.AddMonths(1));

            case RollingInterval.Day:
                return(current.Value.AddDays(1));

            case RollingInterval.Hour:
                return(current.Value.AddHours(1));

            case RollingInterval.Minute:
                return(current.Value.AddMinutes(1));

            default:
                throw new ArgumentException("Invalid rolling interval");
            }
        }
Beispiel #12
0
        private string FormatDate(DateTime dateTime, RollingInterval rollingInterval)
        {
            switch (rollingInterval)
            {
            case RollingInterval.Infinite:
                return("");

            case RollingInterval.Year:
                return(dateTime.ToString("yyyy"));

            case RollingInterval.Month:
                return(dateTime.ToString("yyyyMM"));

            case RollingInterval.Day:
                return(dateTime.ToString("yyyyMMdd"));

            case RollingInterval.Hour:
                return(dateTime.ToString("yyyyMMddhh"));

            case RollingInterval.Minute:
                return(dateTime.ToString("yyyyMMddhhmm"));

            default:
                return(dateTime.ToString("yyyyMMdd"));
            }
        }
Beispiel #13
0
        public string Format(DateTime dateTime, string name, RollingInterval rollingInterval)
        {
            var date        = FormatDate(dateTime, rollingInterval);
            var trimmedName = name.Trim('-'); // Trim for back compatibility with prefixes containing dash on start

            return($"{date}{DateAndNameDelimiter}{trimmedName}.log");
        }
Beispiel #14
0
 /// <remarks>
 ///    Used in config - If renamed or moved to other assembly the config file also has be updated.
 /// </remarks>
 public static LoggerConfiguration File(this LoggerSinkConfiguration configuration, ITextFormatter formatter,
                                        string path,
                                        LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose,
                                        LoggingLevelSwitch levelSwitch         = null,
                                        long?fileSizeLimitBytes         = 1073741824,
                                        TimeSpan?flushToDiskInterval    = null,
                                        RollingInterval rollingInterval = RollingInterval.Infinite,
                                        bool rollOnFileSizeLimit        = false,
                                        int?retainedFileCountLimit      = 31,
                                        Encoding encoding = null
                                        )
 {
     return(configuration.Async(
                asyncConfiguration => asyncConfiguration.Map(AppDomainId, (_, mapConfiguration) =>
                                                             mapConfiguration.File(
                                                                 formatter,
                                                                 path,
                                                                 restrictedToMinimumLevel,
                                                                 fileSizeLimitBytes,
                                                                 levelSwitch,
                                                                 buffered: true,
                                                                 shared: false,
                                                                 flushToDiskInterval,
                                                                 rollingInterval,
                                                                 rollOnFileSizeLimit,
                                                                 retainedFileCountLimit,
                                                                 encoding),
                                                             sinkMapCountLimit: 0)
                ));
 }
        /// <summary>
        /// Write log events to the specified file.
        /// </summary>
        /// <param name="sinkConfiguration">Logger sink configuration.</param>
        /// <param name="path">Path to the file.</param>
        /// <param name="restrictedToMinimumLevel">The minimum level for
        /// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
        /// <param name="levelSwitch">A switch allowing the pass-through minimum level
        /// to be changed at runtime.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        /// the default is "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}".</param>
        /// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow.
        /// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit
        /// will be written in full even if it exceeds the limit.</param>
        /// <param name="buffered">Indicates if flushing to the output file can be buffered or not. The default
        /// is false.</param>
        /// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param>
        /// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param>
        /// <param name="rollingInterval">The interval at which logging will roll over to a new file.</param>
        /// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames
        /// will have a number appended in the format <code>_NNN</code>, with the first filename given no number.</param>
        /// <param name="retainedFileCountLimit">The maximum number of log files that will be retained,
        /// including the current log file. For unlimited retention, pass null. The default is 31.</param>
        /// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        /// <remarks>The file will be written using the UTF-8 character set.</remarks>
        public static LoggerConfiguration File(
            this LoggerSinkConfiguration sinkConfiguration,
            string path,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string outputTemplate          = DefaultOutputTemplate,
            IFormatProvider formatProvider = null,
            long?fileSizeLimitBytes        = DefaultFileSizeLimitBytes,
            LoggingLevelSwitch levelSwitch = null,
            bool buffered = false,
            bool shared   = false,
            TimeSpan?flushToDiskInterval    = null,
            RollingInterval rollingInterval = RollingInterval.Infinite,
            bool rollOnFileSizeLimit        = false,
            int?retainedFileCountLimit      = DefaultRetainedFileCountLimit,
            Encoding encoding = null)
        {
            if (sinkConfiguration == null)
            {
                throw new ArgumentNullException(nameof(sinkConfiguration));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (outputTemplate == null)
            {
                throw new ArgumentNullException(nameof(outputTemplate));
            }

            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            return(File(sinkConfiguration, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes,
                        levelSwitch, buffered, shared, flushToDiskInterval,
                        rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding));
        }
Beispiel #16
0
        public static void Main(string[] args)
        {
            const int             retainedFileCountLimit = 5;                // The maximum number of log files that will be retained (default is 31)
            const long            fileSizeLimitBytes     = 1L * 1024 * 1024; // 1MB (size is in bytes & default is 1 GB)
            const string          defaultOutputTemplate  = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}";
            const RollingInterval rollingInterval        = RollingInterval.Infinite;
            const bool            rollOnFileSizeLimit    = true;

            Log.Logger = new LoggerConfiguration()
                         //.ReadFrom.Configuration(IConfiguration)
                         .Enrich.FromLogContext()
                         .WriteTo.File(new RenderedCompactJsonFormatter(), "Logs\\moviesapi.ndjson",
                                       LogEventLevel.Debug, fileSizeLimitBytes, null, false, false, null,
                                       rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, null)
                         .WriteTo.File("Logs\\moviesapi.txt", LogEventLevel.Debug, defaultOutputTemplate,
                                       null, fileSizeLimitBytes, null, false, false)
                         .WriteTo.Console()
                         .CreateLogger();

            try
            {
                Log.Information("Starting up application");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Beispiel #17
0
        /// <summary>Add a file logger.
        /// </summary>
        /// <param name="loggerName"></param>
        /// <param name="loggerFileName"></param>
        /// <param name="contextPropertyName"></param>
        /// <param name="defaultLoggerFileExtensions"></param>
        /// <param name="defaultLoggerFileOutputTemplate"></param>
        /// <param name="defaultLoggerFileBuffered"></param>
        /// <param name="defaultLoggerFileSizeLimitBytes"></param>
        /// <param name="defaultLoggerFileRollingInterval"></param>
        /// <param name="defaultLoggerFileRollOnFileSizeLimit"></param>
        /// <param name="defaultLoggerFileRetainedFileCountLimit"></param>
        /// <param name="defaultLoggerFileFlushToDiskIntervalSenconds"></param>
        /// <param name="minimumLevel"></param>
        /// <returns></returns>
        public SerilogLoggerFactory AddFileLogger(string loggerName,
                                                  string loggerFileName,
                                                  string contextPropertyName                       = "logger",
                                                  string defaultLoggerFileExtensions               = "-.log",
                                                  string defaultLoggerFileOutputTemplate           = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{logger}] - {Message:lj}{NewLine}{Exception}",
                                                  bool defaultLoggerFileBuffered                   = true,
                                                  long?defaultLoggerFileSizeLimitBytes             = null,
                                                  RollingInterval defaultLoggerFileRollingInterval = RollingInterval.Day,
                                                  bool defaultLoggerFileRollOnFileSizeLimit        = true,
                                                  int?defaultLoggerFileRetainedFileCountLimit      = null,
                                                  int?defaultLoggerFileFlushToDiskIntervalSenconds = 1,
                                                  LogEventLevel minimumLevel                       = LogEventLevel.Information)
        {
            var defaultLoggerFileFlushToDiskInterval = defaultLoggerFileFlushToDiskIntervalSenconds != null ? new TimeSpan(defaultLoggerFileFlushToDiskIntervalSenconds.Value * 1000 * 10000) : default(TimeSpan?);

            _loggerDict.TryAdd(loggerName, new SerilogLogger(contextPropertyName, new LoggerConfiguration()
                                                             .MinimumLevel.Verbose()
                                                             .WriteTo.File(loggerFileName + defaultLoggerFileExtensions,
                                                                           restrictedToMinimumLevel: minimumLevel,
                                                                           outputTemplate: defaultLoggerFileOutputTemplate,
                                                                           buffered: defaultLoggerFileBuffered,
                                                                           fileSizeLimitBytes: defaultLoggerFileSizeLimitBytes,
                                                                           rollingInterval: defaultLoggerFileRollingInterval,
                                                                           rollOnFileSizeLimit: defaultLoggerFileRollOnFileSizeLimit,
                                                                           retainedFileCountLimit: defaultLoggerFileRetainedFileCountLimit,
                                                                           flushToDiskInterval: defaultLoggerFileFlushToDiskInterval)
                                                             .CreateLogger()));
            return(this);
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="RollingFileSink" /> class.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="textFormatter">The text formatter.</param>
        /// <param name="fileSizeLimitBytes">The file size limit bytes.</param>
        /// <param name="retainedFileCountLimit">The retained file count limit.</param>
        /// <param name="encoding">The encoding.</param>
        /// <param name="buffered">if set to <c>true</c> [buffered].</param>
        /// <param name="rollingInterval">The rolling interval.</param>
        /// <param name="rollOnFileSizeLimit">if set to <c>true</c> [roll on file size limit].</param>
        /// <param name="fileLifecycleHooks">The file lifecycle hooks.</param>
        /// <param name="bucketName">The Amazon S3 bucket name.</param>
        /// <param name="endpoint">The Amazon S3 endpoint.</param>
        /// <param name="awsAccessKeyId">The Amazon S3 access key id.</param>
        /// <param name="awsSecretAccessKey">The Amazon S3 access key.</param>
        /// <exception cref="ArgumentNullException">An <see cref="ArgumentNullException" /> thrown when the path is null.</exception>
        /// <exception cref="ArgumentException">
        ///     Negative value provided; file size limit must be non-negative.
        ///     or
        ///     Zero or negative value provided; retained file count limit must be at least 1.
        /// </exception>
        public RollingFileSink(
            string path,
            ITextFormatter textFormatter,
            long?fileSizeLimitBytes,
            int?retainedFileCountLimit,
            Encoding encoding,
            bool buffered,
            RollingInterval rollingInterval,
            bool rollOnFileSizeLimit,
            FileLifecycleHooks fileLifecycleHooks,
            string bucketName,
            RegionEndpoint endpoint,
            string awsAccessKeyId,
            string awsSecretAccessKey)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (string.IsNullOrWhiteSpace(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }

            if (string.IsNullOrWhiteSpace(awsAccessKeyId))
            {
                throw new ArgumentNullException(nameof(awsAccessKeyId));
            }

            if (string.IsNullOrWhiteSpace(awsSecretAccessKey))
            {
                throw new ArgumentNullException(nameof(awsSecretAccessKey));
            }

            if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0)
            {
                throw new ArgumentException("Negative value provided; file size limit must be non-negative.");
            }

            if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1)
            {
                throw new ArgumentException(
                          "Zero or negative value provided; retained file count limit must be at least 1.");
            }

            this.bucketName             = bucketName;
            this.awsAccessKeyId         = awsAccessKeyId;
            this.awsSecretAccessKey     = awsSecretAccessKey;
            this.endpoint               = endpoint;
            this.pathRoller             = new PathRoller(path, rollingInterval);
            this.textFormatter          = textFormatter;
            this.fileSizeLimitBytes     = fileSizeLimitBytes;
            this.retainedFileCountLimit = retainedFileCountLimit;
            this.encoding               = encoding;
            this.buffered               = buffered;
            this.rollOnFileSizeLimit    = rollOnFileSizeLimit;
            this.fileLifecycleHooks     = fileLifecycleHooks;
        }
Beispiel #19
0
        public void ConvertInterval(BufferRollingInterval input, RollingInterval want)
        {
            // Act
            var got = input.ToRollingInterval();

            // Assert
            got.ShouldBe(want);
        }
Beispiel #20
0
 public SerilogServiceLoggerFactory(string logFilePath, RollingInterval fileRollingInterval)
 {
     _serilogLogger = new LoggerConfiguration()
                      .MinimumLevel.Debug()
                      .WriteTo.Console()
                      .WriteTo.File(logFilePath, rollingInterval: fileRollingInterval)
                      .CreateLogger();
 }
Beispiel #21
0
 public FileWriter(IOptions <PipaslotLoggerOptions> options, string name, RollingInterval rollingInterval, IFileNameFormatter fileNameFormatter, QueueFormatter formatter)
 {
     _options           = options;
     _name              = name;
     _formatter         = formatter;
     _rollingInterval   = rollingInterval;
     _fileNameFormatter = fileNameFormatter;
 }
 /// <summary>
 ///
 /// </summary>
 public SeriLog()
 {
     FileName = System.AppDomain.CurrentDomain.FriendlyName;
     SplitFileByLogEventLevel = true;
     rollingInterval          = RollingInterval.Minute;
     FilePath       = "logs\\";
     outputTemplate = "Date : {Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}{NewLine}{Message:lj}{NewLine}======================================================================================================{NewLine}";
 }
Beispiel #23
0
        public LoggerFactory(StrategyMode strategyMode, string logConfigFileName, RollingInterval rollingInterval)
        {
            var config = ReadConfig(GetConfigPath(), logConfigFileName);

            this._logConfig       = JsonConvert.DeserializeObject <LogConfiguration>(config);
            this._logPath         = GetLogPath(strategyMode, this._logConfig);
            this._rollingInterval = rollingInterval;
        }
 /// <summary>
 ///     LogRecord single message with specified log level and class or methods. Useful when you need separate specific procedure
 /// </summary>
 public static void AddTreeLogger(this ILoggingBuilder builder, string name, RollingInterval rollingInterval, params string[] namespaceOrClass)
 {
     builder.AddPipaslotLoggerProvider();
     builder.Services.AddSingleton(s =>
     {
         var logWriterFactory = s.GetService <IFileWriterFactory>();
         var writer           = logWriterFactory.Create(name, rollingInterval);
         return(new Pipe(writer, new TreeQueueFilter(namespaceOrClass)));
     });
 }
Beispiel #25
0
        public void NextIntervalTests(RollingInterval interval, DateTime instant, DateTime?currentCheckpoint, DateTime?nextCheckpoint)
        {
            var current = interval.GetCurrentCheckpoint(instant);

            Assert.Equal(currentCheckpoint, current);

            var next = interval.GetNextCheckpoint(instant);

            Assert.Equal(nextCheckpoint, next);
        }
Beispiel #26
0
        public LoggerFactory(StrategyMode strategyMode, LogConfiguration logConfig, RollingInterval rollingInterval, string identifierPlaceHolder, string searchStringTemplate, List <string> indentifierValues)
        {
            this._logConfig       = logConfig;
            this._logPath         = GetLogPath(strategyMode, logConfig);
            this._rollingInterval = rollingInterval;

            this._identifierPlaceHolder = identifierPlaceHolder;
            this._searchStringTemplate  = searchStringTemplate;
            this._indentifierValues     = indentifierValues;
        }
        /// <summary>   Initializes a new instance of the <see cref="RollingFileSink" /> class. </summary>
        /// <exception cref="ArgumentNullException">
        ///     An <see cref="ArgumentNullException" /> thrown
        ///     when the path is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     Negative value provided; file size limit must be
        ///     non-negative. or Zero or negative value provided;
        ///     retained file count limit must be at least 1.
        /// </exception>
        /// <param name="path">                     The path. </param>
        /// <param name="textFormatter">            The text formatter. </param>
        /// <param name="fileSizeLimitBytes">       The file size limit bytes. </param>
        /// <param name="retainedFileCountLimit">   The retained file count limit. </param>
        /// <param name="encoding">                 The encoding. </param>
        /// <param name="buffered">                 if set to <c>true</c> [buffered]. </param>
        /// <param name="rollingInterval">          The rolling interval. </param>
        /// <param name="rollOnFileSizeLimit">      if set to <c>true</c> [roll on file size limit]. </param>
        /// <param name="fileLifecycleHooks">       The file lifecycle hooks. </param>
        /// <param name="bucketName">               The Amazon S3 bucket name. </param>
        /// <param name="endpoint">                 The Amazon S3 endpoint. </param>
        /// <param name="autoUploadEvents">         Automatically upload all events immediately. </param>
        /// <param name="failureCallback">          (Optional) The failure callback. </param>
        /// <param name="bucketPath">               (Optional) The Amazon S3 bucket path. </param>
        public RollingFileSink(
            string path,
            ITextFormatter textFormatter,
            long?fileSizeLimitBytes,
            int?retainedFileCountLimit,
            Encoding encoding,
            bool buffered,
            RollingInterval rollingInterval,
            bool rollOnFileSizeLimit,
            FileLifecycleHooks fileLifecycleHooks,
            string bucketName,
            RegionEndpoint endpoint,
            bool autoUploadEvents,
            Action <Exception> failureCallback = null,
            string bucketPath = null)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (string.IsNullOrWhiteSpace(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }

            if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0)
            {
                throw new ArgumentException("Negative value provided; file size limit must be non-negative.");
            }

            if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1)
            {
                throw new ArgumentException(
                          "Zero or negative value provided; retained file count limit must be at least 1.");
            }

            if (failureCallback != null)
            {
                this.FailureCallback = failureCallback;
            }

            this.bucketName             = bucketName;
            this.endpoint               = endpoint;
            this.pathRoller             = new PathRoller(path, rollingInterval);
            this.textFormatter          = textFormatter;
            this.fileSizeLimitBytes     = fileSizeLimitBytes;
            this.retainedFileCountLimit = retainedFileCountLimit;
            this.encoding               = encoding;
            this.buffered               = buffered;
            this.rollOnFileSizeLimit    = rollOnFileSizeLimit;
            this.fileLifecycleHooks     = fileLifecycleHooks;
            this.autoUploadEvents       = autoUploadEvents;
            this.bucketPath             = bucketPath;
        }
Beispiel #28
0
        public LoggerFactory(StrategyMode strategyMode, string logConfigFileName, RollingInterval rollingInterval, string identifierPlaceHolder, string searchStringTemplate, List <string> indentifierValues)
        {
            var config = ReadConfig(GetConfigPath(), logConfigFileName);

            this._logConfig       = JsonConvert.DeserializeObject <LogConfiguration>(config);
            this._logPath         = GetLogPath(strategyMode, this._logConfig);
            this._rollingInterval = rollingInterval;

            this._identifierPlaceHolder = identifierPlaceHolder;
            this._searchStringTemplate  = searchStringTemplate;
            this._indentifierValues     = indentifierValues;
        }
        public static LoggerConfiguration AddFileLoggerFilePerLevel(this LoggerConfiguration conf,
                                                                    string rootDirectory, string filename,
                                                                    LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose,
                                                                    string outputTemplate          = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}{NewLine}",
                                                                    IFormatProvider formatProvider = null,
                                                                    long?fileSizeLimitBytes        = 1073741824L, LoggingLevelSwitch levelSwitch = null,
                                                                    bool buffered = false, bool shared = false, TimeSpan?flushToDiskInterval = null,
                                                                    RollingInterval rollingInterval = RollingInterval.Infinite, bool rollOnFileSizeLimit = false,
                                                                    int?retainedFileCountLimit      = 31, Encoding encoding = null,
                                                                    FileLifecycleHooks hooks        = null, TimeSpan?retainedFileTimeLimit = null)
        {
            conf = conf
                   .WriteTo.Logger(lc => lc
                                   .Filter.ByIncludingOnly(m => m.Level == global::Serilog.Events.LogEventLevel.Verbose)
                                   .WriteTo.File(CombinePath(rootDirectory, "Verbose", filename), restrictedToMinimumLevel, outputTemplate, formatProvider,
                                                 fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit,
                                                 retainedFileCountLimit, encoding, hooks, retainedFileTimeLimit)
                                   )
                   .WriteTo.Logger(lc => lc
                                   .Filter.ByIncludingOnly(m => m.Level == global::Serilog.Events.LogEventLevel.Debug)
                                   .WriteTo.File(CombinePath(rootDirectory, "Debug", filename), restrictedToMinimumLevel, outputTemplate, formatProvider,
                                                 fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit,
                                                 retainedFileCountLimit, encoding, hooks, retainedFileTimeLimit)
                                   )
                   .WriteTo.Logger(lc => lc
                                   .Filter.ByIncludingOnly(m => m.Level == global::Serilog.Events.LogEventLevel.Information)
                                   .WriteTo.File(CombinePath(rootDirectory, "Info", filename), restrictedToMinimumLevel, outputTemplate, formatProvider,
                                                 fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit,
                                                 retainedFileCountLimit, encoding, hooks, retainedFileTimeLimit)
                                   )
                   .WriteTo.Logger(lc => lc
                                   .Filter.ByIncludingOnly(m => m.Level == global::Serilog.Events.LogEventLevel.Warning)
                                   .WriteTo.File(CombinePath(rootDirectory, "Warn", filename), restrictedToMinimumLevel, outputTemplate, formatProvider,
                                                 fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit,
                                                 retainedFileCountLimit, encoding, hooks, retainedFileTimeLimit)
                                   )
                   .WriteTo.Logger(lc => lc
                                   .Filter.ByIncludingOnly(m => m.Level == global::Serilog.Events.LogEventLevel.Error)
                                   .WriteTo.File(CombinePath(rootDirectory, "Error", filename), restrictedToMinimumLevel, outputTemplate, formatProvider,
                                                 fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit,
                                                 retainedFileCountLimit, encoding, hooks, retainedFileTimeLimit)
                                   )
                   .WriteTo.Logger(lc => lc
                                   .Filter.ByIncludingOnly(m => m.Level == global::Serilog.Events.LogEventLevel.Fatal)
                                   .WriteTo.File(CombinePath(rootDirectory, "Fatal", filename), restrictedToMinimumLevel, outputTemplate, formatProvider,
                                                 fileSizeLimitBytes, levelSwitch, buffered, shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit,
                                                 retainedFileCountLimit, encoding, hooks, retainedFileTimeLimit)
                                   );


            return(conf);
        }
Beispiel #30
0
        public FileSinkOptions AddStrategy(
            string strategyName,
            string fileName,
            PathType pathType               = PathType.Relative,
            TimeSpan?flushToDiskInterval    = null,
            RollingInterval rollingInterval = RollingInterval.Infinite,
            List <string> namespaceList     = null, string outputTemplate = null)
        {
            if (string.IsNullOrWhiteSpace(strategyName))
            {
                throw new ArgumentNullException(nameof(strategyName));
            }
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            var u = $"{_registeredPath}-{pathType.GetName()}";

            if (_registeredPath.Contains(u))
            {
                throw new ArgumentException("Multiple definitions");
            }
            if (string.IsNullOrWhiteSpace(outputTemplate))
            {
                outputTemplate = RealDefaultOutputTemplate;
            }
            if (namespaceList == null || !namespaceList.Any())
            {
                namespaceList = new List <string> {
                    "*"
                }
            }
            ;

            OutputOptionsInternal.Add(
                strategyName,
                new OutputOptions {
                Path                = fileName,
                Template            = outputTemplate,
                PathType            = pathType,
                FlushToDiskInterval = flushToDiskInterval,
                Rolling             = rollingInterval,
                Navigators          = namespaceList
            });
            _registeredPath.Add(u);

            return(this);
        }

        #endregion
    }