terça-feira, novembro 23, 2021

NLOG - Archieve - Changing the name of the file to be compressed

In a given scenario I needed to keep the log name, however, when compressing I needed to change the file name. The easiest way to do this is to change NLog.Targets.FileTarget.FileCompressor, remembering that it is a static attribute and will affect all other logs. 1. Create a class with IFileCompresso interface with you logic, in my case I set the name iquals to zip file but .txt at the end. 

using NLog.Targets;
using System.IO;
using System.IO.Compression;

namespace LogManager
{
    internal class MyZipFileCompressor : IFileCompressor
    {        
        internal MyZipFileCompressor () { }

        public void CompressFile(string fileName, string archiveFileName)
        {
           
            string entryName =  Path.GetFileNameWithoutExtension(archiveFileName) +".txt";
            using (var archiveStream = new FileStream(archiveFileName, FileMode.Create))
            using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create))
            using (var originalFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var zipArchiveEntry = archive.CreateEntry(entryName);
                using (var destination = zipArchiveEntry.Open())
                {
                    originalFileStream.CopyTo(destination);
                }
            }

        }
    }

}

//when you start your Target juset set your compressor
 _logFileTarget.FileCompressor = new MyZipFileCompressor ();