Skip to content

Instantly share code, notes, and snippets.

@KamranShahid
Created February 4, 2020 15:07
Show Gist options
  • Save KamranShahid/cbb2d04691b0862938b72d83100e9e93 to your computer and use it in GitHub Desktop.
Save KamranShahid/cbb2d04691b0862938b72d83100e9e93 to your computer and use it in GitHub Desktop.
log4net archiving on log rotation
public class CustomRollingFileAppender : RollingFileAppender
{
private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected override void AdjustFileBeforeAppend()
{
var previousFile = File;
base.AdjustFileBeforeAppend();
if (File != previousFile)
{
try
{
FileInfo fa = new FileInfo(previousFile);
if (System.IO.File.Exists(fa.FullName + ".zip"))
{
using (ZipArchive zip = ZipFile.Open(fa.FullName + ".zip", ZipArchiveMode.Update))
{
if (zip.Entries != null && zip.Entries.Count > 0)
{
zip.CreateEntryFromFile(fa.FullName, fa.Name + "." + zip.Entries.Count.ToString());
}
else
{
zip.CreateEntryFromFile(fa.FullName, fa.Name);
}
}
}
else
{
using (ZipArchive zip = ZipFile.Open(fa.FullName + ".zip", ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(fa.FullName, fa.Name);
}
}
System.IO.File.Delete(fa.FullName);
}
catch (Exception ex)
{
Logger.Fatal("Error While archiving Zip File :" + ex.Message);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment