void CloseFile()
        {
            if (_currentFile != null)
            {
                (_currentFile as IDisposable)?.Dispose();
                _currentFile = null;
            }

            _nextCheckpoint = null;
        }
        /// <summary>   Closes the file. </summary>
        private void CloseFile()
        {
            if (this.currentFile != null)
            {
                (this.currentFile as IDisposable)?.Dispose();
                this.currentFile = null;
            }

            this.nextCheckpoint = null;
        }
 /// <summary>
 /// Copies the <see cref="IFileSource"/> to an <see cref="IFileSink"/>.
 /// </summary>
 /// <param name="sourceFileSource">The source file source.</param>
 /// <param name="targetFileSink">The target file sink.</param>
 public static void CopyTo(this IFileSource sourceFileSource, IFileSink targetFileSink)
 {
     foreach (string file in sourceFileSource.Files)
     {
         using (Stream inputStream = sourceFileSource.OpenFile(file))
             using (Stream outputStream = targetFileSink.CreateFile(file))
             {
                 inputStream.CopyTo(outputStream);
             }
     }
 }
        void OpenFile(DateTime now, int?minSequence = null)
        {
            var currentCheckpoint = _roller.GetCurrentCheckpoint(now);

            // We only try periodically because repeated failures
            // to open log files REALLY slow an app down.
            _nextCheckpoint = _roller.GetNextCheckpoint(now) ?? now.AddMinutes(30);

            var existingFiles = Enumerable.Empty <string>();

            try
            {
                existingFiles = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern)
                                .Select(Path.GetFileName);
            }
            catch (DirectoryNotFoundException) { }

            var latestForThisCheckpoint = _roller
                                          .SelectMatches(existingFiles)
                                          .Where(m => m.DateTime == currentCheckpoint)
                                          .OrderByDescending(m => m.SequenceNumber)
                                          .FirstOrDefault();

            var sequence = latestForThisCheckpoint?.SequenceNumber;

            if (minSequence != null)
            {
                if (sequence == null || sequence.Value < minSequence.Value)
                {
                    sequence = minSequence;
                }
            }

            const int maxAttempts = 3;

            for (var attempt = 0; attempt < maxAttempts; attempt++)
            {
                _roller.GetLogFilePath(now, sequence, out var path);

                try
                {
                    _currentFile = _shared ?
                                   (IFileSink) new SharedFileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding) :
                                   new FileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered);
                    _currentFileSequence = sequence;
                }
                catch (IOException ex)
                {
                    if (IOErrors.IsLockedFile(ex))
                    {
                        SelfLog.WriteLine("File target {0} was locked, attempting to open next in sequence (attempt {1})", path, attempt + 1);
                        sequence = (sequence ?? 0) + 1;
                        continue;
                    }

                    throw;
                }

                ApplyRetentionPolicy(path);
                return;
            }
        }
        /// <summary>   Opens the file. </summary>
        /// <exception cref="DirectoryNotFoundException">
        ///     Thrown when the requested directory is not
        ///     present.
        /// </exception>
        /// <exception cref="IOException">                  Thrown when an IO failure occurred. </exception>
        /// <param name="now">          The now. </param>
        /// <param name="minSequence">  (Optional) The minimum sequence. </param>
        private void OpenFile(DateTime now, int?minSequence = null)
        {
            var currentCheckpoint = this.pathRoller.GetCurrentCheckpoint(now);

            // We only try periodically because repeated failures
            // to open log files REALLY slow an app down.
            this.nextCheckpoint = this.pathRoller.GetNextCheckpoint(now) ?? now.AddMinutes(30);

            var existingFiles = Enumerable.Empty <string>();

            try
            {
                if (Directory.Exists(this.pathRoller.LogFileDirectory))
                {
                    existingFiles = Directory.GetFiles(
                        this.pathRoller.LogFileDirectory,
                        this.pathRoller.DirectorySearchPattern).Select(Path.GetFileName);
                }
            }
            catch (DirectoryNotFoundException)
            {
                SelfLog.WriteLine("Temporary log directory is not found");
                throw;
            }

            var latestForThisCheckpoint = this.pathRoller.SelectMatches(existingFiles)
                                          .Where(m => m.DateTime == currentCheckpoint).OrderByDescending(m => m.SequenceNumber).FirstOrDefault();

            var sequence = latestForThisCheckpoint?.SequenceNumber;

            if (minSequence != null && (sequence == null || sequence.Value < minSequence.Value))
            {
                sequence = minSequence;
            }

            const int MaxAttempts = 3;

            for (var attempt = 0; attempt < MaxAttempts; attempt++)
            {
                this.pathRoller.GetLogFilePath(now, sequence, out var path);

                try
                {
                    this.currentFile = new FileSink(
                        path,
                        this.textFormatter,
                        this.fileSizeLimitBytes,
                        this.encoding,
                        this.buffered,
                        this.fileLifecycleHooks);

                    this.currentFileName = path;

                    this.currentFileSequence = sequence;
                }
                catch (IOException ex)
                {
                    if (!IoErrors.IsLockedFile(ex))
                    {
                        throw;
                    }

                    SelfLog.WriteLine(
                        "File target {0} was locked, attempting to open next in sequence (attempt {1})",
                        path,
                        attempt + 1);
                    sequence = (sequence ?? 0) + 1;
                    continue;
                }

                this.ApplyRetentionPolicy(path);
                return;
            }
        }
Esempio n. 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TsSymbolWriter"/> class.
 /// </summary>
 /// <param name="fileSink">The file sink.</param>
 public TsSymbolWriter(IFileSink fileSink)
 {
     this.fileSink = fileSink;
 }
        void OpenFile(DateTime now, int?minSequence = null)
        {
            var currentCheckpoint = _roller.GetCurrentCheckpoint(now);

            // We only try periodically because repeated failures
            // to open log files REALLY slow an app down.

            var existingFiles = Enumerable.Empty <string>();

            try
            {
                if (Directory.Exists(_roller.LogFileDirectory))
                {
                    existingFiles = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern)
                                    .Select(Path.GetFileName);
                }
            }
            catch (DirectoryNotFoundException)
            {
            }

            var latestForThisCheckpoint = _roller
                                          .SelectMatches(existingFiles)
                                          .Where(m => m.DateTime == currentCheckpoint)
                                          .OrderByDescending(m => m.SequenceNumber)
                                          .FirstOrDefault();

            var sequence = latestForThisCheckpoint?.SequenceNumber;

            if (_keepFilename)
            {
                //Sequence number calculation is wrong when keeping filename. If there is an existing log file, latestForThisCheckpoint won't be null but will report
                // a sequence number of 0 because filename will be (log.txt), if there are two files: sequence number will report 1 (log.txt, log-001.txt).
                // But it should report 1 in the first case and 2 in the second case.
                //
                if (sequence == null)
                {
                    if (latestForThisCheckpoint != null)
                    {
                        sequence = 1;
                    }
                }
                else
                {
                    sequence++;
                }
            }
            if (minSequence != null)
            {
                if (sequence == null || sequence.Value < minSequence.Value)
                {
                    sequence = minSequence;
                }
            }

            if (_keepFilename)
            {
                const int maxAttempts = 3;

                // if current file exists we rename it with rolling date
                //we lock this portion of the code to avoid another process in shared mode to move the file
                //at the same time we are moving it. It might result in a missing file exception, because the second thread will try to move a file that has
                //been already moved.
                lock (_syncLock)
                {
                    _roller.GetLogFilePath(out var currentPath);
                    var fileInfo = new FileInfo(currentPath);
                    //we check of we have reach file size limit, if not we keep the same file. If we dont have roll on file size enable, we will create a new file as soon as one exists even if it is empty.
                    if (File.Exists(currentPath) && MustRoll(now) && (_rollOnFileSizeLimit ? fileInfo.Length >= _fileSizeLimitBytes : fileInfo.Length > 0))
                    {
                        for (var attempt = 0; attempt < maxAttempts; attempt++)
                        {
                            _roller.GetLogFilePath(_useLastWriteAsTimestamp ? fileInfo.LastWriteTime : now,
                                                   sequence, out var path);
                            try
                            {
                                System.IO.File.Move(currentPath, path);
                                _currentFileSequence = sequence;
                            }
                            catch (IOException ex)
                            {
                                if (IOErrors.IsLockedFile(ex) || File.Exists(path))
                                {
                                    SelfLog.WriteLine(
                                        "File target {0} was locked or exists, attempting to open next in sequence (attempt {1})",
                                        path, attempt + 1);
                                    sequence = (sequence ?? 0) + 1;
                                    continue;
                                }

                                throw;
                            }

                            break;
                        }
                    }

                    //now we open the current file
                    try
                    {
                        _currentFile = _shared
                            ?
    #pragma warning disable 618
                                       (IFileSink) new SharedFileSink(currentPath, _textFormatter, _fileSizeLimitBytes, _encoding)
                            :
    #pragma warning restore 618
                                       new FileSink(currentPath, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered, _hooks);
                    }
                    catch (IOException ex)
                    {
                        if (IOErrors.IsLockedFile(ex))
                        {
                            SelfLog.WriteLine("File target {0} was locked, this should not happen", currentPath);
                        }

                        throw;
                    }

                    ApplyRetentionPolicy(currentPath);
                }
            }
            else
            {
                const int maxAttempts = 3;
                for (var attempt = 0; attempt < maxAttempts; attempt++)
                {
                    _roller.GetLogFilePath(now, sequence, out var path);

                    try
                    {
                        _currentFile = _shared
                            ?
#pragma warning disable 618
                                       (IFileSink) new SharedFileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding)
                            :
#pragma warning restore 618
                                       new FileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered, _hooks);

                        _currentFileSequence = sequence;
                    }
                    catch (IOException ex)
                    {
                        if (IOErrors.IsLockedFile(ex))
                        {
                            SelfLog.WriteLine(
                                "File target {0} was locked, attempting to open next in sequence (attempt {1})", path,
                                attempt + 1);
                            sequence = (sequence ?? 0) + 1;
                            continue;
                        }

                        throw;
                    }

                    ApplyRetentionPolicy(path);
                    return;
                }
            }

            _nextCheckpoint = _roller.GetNextCheckpoint(now) ?? now.AddMinutes(30);
        }
Esempio n. 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AuditingFileSink"/> class.
 /// </summary>
 /// <param name="fileSink">The file sink.</param>
 public AuditingFileSink(IFileSink fileSink)
 {
     this.fileSink = fileSink;
 }