Accessing and saving the IIS log from a Windows Azure WebRole

by ingvar 28. september 2011 21:36

A Windows Azure WebRoles may get recycled due to crashes, maintenance or other things. And because a WebRole is a VM, all changed/added files are lost when it gets recycled. This includes the IIS server logs. For many reasons, these servers logs would be nice to save outside the WebRole, so they don’t get lost if/when a WebRole gets recycled. I have found a nice way of saving these logs files to the blob storage. The code could easily be modified to other things with the log files.

The web role needs to have elevated privileges. This is done by adding the following element to the WebRole element in the ServiceDefinition.csdef file.


<Runtime executionContext="elevated" />

And here is the code needed to access the IIS log files:

CloudBlobContainer container = null; /* Initalize this */

Regex regex = new Regex(@"(?<string>\%[^\%]*\%)");

ServerManager serverManager = new ServerManager();

foreach (Site site in serverManager.Sites)
{
/* Resolve enviroment path */
string directory = regex.Replace(
site.LogFile.Directory,
m => Environment.ExpandEnvironmentVariables(m.Groups["string"].Value)
);

if (!Directory.Exists(directory)) continue;

IEnumerable<string> files =
Directory.GetFiles(directory, "*.log", SearchOption.AllDirectories);
foreach (string filePath in )
{
/* Avoid name clashes if we have multi instances */
string blobName =
string.Format("{0}_{1}", site.Name, Path.GetFileName(filePath));

CloudBlob blob = container.GetBlobReference(blobName);

/* Only upload new or written to log files */
if (!blob.Exists() ||
blob.Properties.LastModifiedUtc < File.GetLastWriteTimeUtc(filePath))
{
blob.UploadFile(filePath);
}
}
}

I use an extension method on the blob called Exists. See the implementation for it here.

Tags:

About the author

Martin Ingvar Kofoed Jensen

Architect and Senior Developer at Composite on the open source project Composite C1 - C#/4.0, LINQ, Azure, Parallel and much more!

Follow me on Twitter

Read more about me here.

Read press and buzz about my work and me here.

Stack Overflow

Month List