public TemplatedPathRoller(string pathTemplate)
        {
            if (pathTemplate == null)
            {
                throw new ArgumentNullException(nameof(pathTemplate));
            }

            var directory = Path.GetDirectoryName(pathTemplate);

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

            Specifier directorySpecifier;

            if (Specifier.TryGetSpecifier(directory, out directorySpecifier))
            {
                throw new ArgumentException($"The {directorySpecifier.Token} specifier cannot form part of the directory name.");
            }

            directory = Path.GetFullPath(directory);

            var filenameTemplate = Path.GetFileName(pathTemplate);

            if (!Specifier.TryGetSpecifier(filenameTemplate, out _specifier))
            {
                _specifier       = Specifier.Date;
                filenameTemplate = Path.GetFileNameWithoutExtension(filenameTemplate) + DefaultSeparator +
                                   _specifier.Token + Path.GetExtension(filenameTemplate);
            }

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

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

            DirectorySearchPattern = filenameTemplate.Replace(_specifier.Token, "*");
            LogFileDirectory       = directory;
            _pathTemplate          = Path.Combine(LogFileDirectory, filenameTemplate);
        }
Ejemplo n.º 2
0
        public static bool TryGetSpecifier(string pathTemplate, out Specifier specifier)
        {
            if (pathTemplate == null)
            {
                throw new ArgumentNullException(nameof(pathTemplate));
            }

            var specifiers = new[] { HalfHour, Hour, Date }.Where(s => pathTemplate.Contains(s.Token)).ToArray();

            if (specifiers.Length > 1)
            {
                throw new ArgumentException("Only one interval specifier can be used in a rolling log file path.", nameof(pathTemplate));
            }

            specifier = specifiers.FirstOrDefault();
            return(specifier != null);
        }