我正在使用系统诊断跟踪记录来在我的应用程序中进行日志记录。我想将日志文件上传到Azure存储。我能够这样做,但是只能通过上传存储在我的项目文件夹中的日志来做到。我创建了一个自定义的跟踪侦听器来定向文件的上传位置。
public TextLogTraceListener(string filePath, string db)
{
filePath = filePath + db + "\\" + DateTime.Now.ToString("MMddyyyy") + "_mylog.log";
logFileLocation = filePath;
traceWriter = new StreamWriter(filePath, true);
traceWriter.AutoFlush = true;
}
在另一个功能中,我正在使用以下代码将存储在项目文件夹中的日志文件上传到Azure存储空间
using (var fileStream = File.OpenRead(path))
{
blockBlob.UploadFromStream(fileStream);
}
但是,我想削减中间人并将日志直接上传到Azure存储。我该怎么办?
如果要使用Azure blob存储作为日志文件系统,我们可以使用Azure append blob存储日志文件。
例如
public class BlobWriterStorageListener : TraceListener
{
// Install package Microsoft.Azure.Storage.Blob
protected override string[] GetSupportedAttributes()
{
return new[] { "StorageConnectionString", "LogsContainerName", "LogFileName" };
}
public override void Write(string message, string category) {
string stroageConnectionString = Attributes["StorageConnectionString"];
string logsContainerName = Attributes["LogsContainerName"];
string logFileName = Attributes["LogFileName"];
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(stroageConnectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(logsContainerName);
container.CreateIfNotExists();
CloudAppendBlob appendBlob = container.GetAppendBlobReference(logFileName);
// when the blob does not exist, create it.
if (!appendBlob.Exists()) {
appendBlob.CreateOrReplace();
}
appendBlob.AppendText(String.Format("[Timestamp: {2:u}] Message:{0} Category:{1}", message, category, DateTime.UtcNow));
}
public override void WriteLine(string message, string category)
{
Write(message, category +"\n");
}
public override void Write(string message)
{
Write(message, null);
}
public override void WriteLine(string message)
{
Write(message + "\n");
}
static void Main(string[] args)
{
TraceListener ooblistener = new BlobWriterStorageListener();
ooblistener.Name = "AzureBlobStorageListener";
ooblistener.Attributes.Add("type", "BlobTrace.BlobWriterStorageListener");
ooblistener.Attributes.Add("StorageConnectionString", "<your storage connection string>");
ooblistener.Attributes.Add("LogsContainerName", "logs");
ooblistener.Attributes.Add("LogFileName", "application.log");
Trace.Listeners.Add(ooblistener);
Trace.WriteLine("Hey There!!", EventLogEntryType.Information.ToString());
Thread.Sleep(60000);
Trace.WriteLine("Hey Here!!", EventLogEntryType.Information.ToString());
Console.ReadLine();
}