Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Created November 16, 2014 07:25
Show Gist options
  • Save davidfowl/67c3e3606a4ed947814f to your computer and use it in GitHub Desktop.
Save davidfowl/67c3e3606a4ed947814f to your computer and use it in GitHub Desktop.
AzureStreamingLoggerProvider
public class AzureStreamingLoggerProvider : ILoggerProvider
{
public ILogger Create(string name)
{
return new AzureLogger(name);
}
private class AzureLogger : ILogger
{
private readonly string _name;
private readonly object _writerLock = new object();
private int? _numFiles;
private int _numLines;
private const int MaxLines = 1000;
public AzureLogger(string name)
{
_name = name;
}
public IDisposable BeginScope(object state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Write(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
{
var message = string.Empty;
if (formatter != null)
{
message = formatter(state, exception);
}
else
{
if (state != null)
{
message += state;
}
if (exception != null)
{
message += Environment.NewLine + exception;
}
}
if (string.IsNullOrEmpty(message))
{
return;
}
var severity = logLevel.ToString().ToUpperInvariant();
Log(string.Format("[{0}:{1}] {2}", severity, _name, message));
}
private void Log(string text)
{
var applicationLogFilesPath = Path.Combine(Environment.GetEnvironmentVariable("HOME"), "LogFiles", "Application");
lock (_writerLock)
{
if (_numFiles == null || _numLines > MaxLines)
{
if (_numFiles == null)
{
var fileNumbers = Directory.GetFiles(applicationLogFilesPath, "logs_*.txt")
.Select(Path.GetFileNameWithoutExtension)
.Select(p => p.Substring("logs_".Length))
.Select(Int32.Parse);
if (fileNumbers.Any())
{
_numFiles = fileNumbers.Max();
}
}
_numFiles = _numFiles ?? 0;
_numLines = 0;
_numFiles++;
Directory.CreateDirectory(applicationLogFilesPath);
}
var path = Path.Combine(applicationLogFilesPath, "logs_" + _numFiles + ".txt");
File.AppendAllText(path, text + Environment.NewLine);
_numLines++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment