Exemplo n.º 1
0
        public static bool TryGetRollingFrequency(string pathTemplate, out RollingFrequency specifier)
        {
            if (pathTemplate == null)
            {
                throw new ArgumentNullException(nameof(pathTemplate));
            }
            var frequencies = new[] { Date, Hour }.Where(s => pathTemplate.Contains(s.Name)).ToArray();

            specifier = frequencies.LastOrDefault();
            return(specifier != null);
        }
Exemplo n.º 2
0
        // Rolls files based on the current date, using a path formatting pattern like: Logs/log-{Date}.txt
        public RollingFilePath(string pathTemplate)
        {
            if (pathTemplate == null)
            {
                throw new ArgumentNullException(nameof(pathTemplate));
            }

            var filenameTemplate = Path.GetFileName(pathTemplate);

            if (!RollingFrequency.TryGetRollingFrequency(filenameTemplate, out _frequency))
            {
                _frequency       = RollingFrequency.Date;
                filenameTemplate = Path.GetFileNameWithoutExtension(filenameTemplate) + DefaultSeparator +
                                   _frequency.Name + Path.GetExtension(filenameTemplate);
            }

            var indexOfSpecifier = filenameTemplate.IndexOf(_frequency.Name, StringComparison.Ordinal);
            var prefix           = filenameTemplate.Substring(0, indexOfSpecifier);
            var suffix           = filenameTemplate.Substring(indexOfSpecifier + _frequency.Name.Length);

            _filenameMatcher = new Regex(
                "^" +
                Regex.Escape(prefix) +
                "(?<" + SpecifierMatchGroup + ">\\d{" + _frequency.Format.Length + "})" +
                "(?<" + SequenceNumberMatchGroup + ">_[0-9]{3,}){0,1}" +
                Regex.Escape(suffix) +
                "$");

            FileSearchPattern = filenameTemplate.Replace(_frequency.Name, "*");
            var directory = Path.GetDirectoryName(pathTemplate);

            if (string.IsNullOrEmpty(directory))
            {
                directory = Directory.GetCurrentDirectory();
            }
            else
            {
                directory = Path.GetFullPath(directory);
            }
            LogFileDirectory = directory;
            _pathTemplate    = Path.Combine(LogFileDirectory, filenameTemplate);
        }