/// <summary> /// Create a log file scanner /// </summary> /// <param name="pathAndMask">File path and mask (i.e. /var/log/auth*.log)</param> /// <param name="maxFileSizeBytes">Max size of file (in bytes) before it is deleted or 0 for unlimited</param> /// <param name="fileProcessingIntervalMilliseconds">How often to process files, in milliseconds, less than 1 for manual processing, in which case <see cref="ProcessFiles"/> must be called as needed.</param> /// <param name="encoding">Encoding or null for utf-8. The encoding must either be single or variable byte, like ASCII, Ansi, utf-8, etc. UTF-16 and the like are not supported.</param> /// <param name="maxLineLength">Maximum line length before considering the file a binary file and failing</param> public LogFileScanner(string pathAndMask, long maxFileSizeBytes = 0, int fileProcessingIntervalMilliseconds = 0, Encoding encoding = null, int maxLineLength = 8192) { // replace env vars in path/mask PathAndMask = pathAndMask?.Trim().Replace('\\', '/'); PathAndMask.ThrowIfNullOrEmpty(nameof(pathAndMask), "Must pass a non-empty path and mask to log file scanner"); // set properties this.maxFileSize = maxFileSizeBytes; this.encoding = encoding ?? Encoding.UTF8; this.maxLineLength = maxLineLength; try { // add initial files foreach (WatchedFile file in LogFileScanner.GetFiles(PathAndMask)) { watchedFiles.Add(file); } } catch { // generally catching all exceptions and not reporting is bad, but in this case we don't care, // we will try to get files on every ProcessFiles call and can throw the exception then } // setup timer to process files if (fileProcessingIntervalMilliseconds > 0) { fileProcessingTimer = new System.Timers.Timer(fileProcessingIntervalMilliseconds); fileProcessingTimer.Elapsed += (sender, args) => ProcessFiles(); fileProcessingTimer.Start(); } }
/// <summary> /// Create a log file scanner /// </summary> /// <param name="pathAndMask">File path and mask (i.e. /var/log/auth*.log)</param> /// <param name="recursive">Whether to parse all sub directories of path and mask recursively</param> /// <param name="maxFileSizeBytes">Max size of file (in bytes) before it is deleted or 0 for unlimited</param> /// <param name="pingIntervalMilliseconds">Ping interval in milliseconds, less than 1 for manual ping required</param> public IPBanLogFileScanner(string pathAndMask, bool recursive, long maxFileSizeBytes = 0, int pingIntervalMilliseconds = 0) { PathAndMask = pathAndMask?.Trim(); PathAndMask.ThrowIfNullOrEmpty(nameof(pathAndMask), "Must pass a non-empty path and mask to log file scanner"); this.maxFileSize = maxFileSizeBytes; directoryToWatch = Path.GetDirectoryName(pathAndMask); fileMask = Path.GetFileName(pathAndMask); if (pingIntervalMilliseconds > 0) { pingTimer = new System.Timers.Timer(pingIntervalMilliseconds); pingTimer.Elapsed += PingTimerElapsed; pingTimer.Start(); } ScanForFiles(pathAndMask, recursive); }