Before I discovered that working with Azure’s table storage was not the be all and end all that I had once thought (see previous post), I put together some base classes that implement the key recommendations from the Whitepaper for Programming Table Storage.
These classes make working with Microsoft.WindowsAzure.StorageClient a little easier and less verbose, and means that you can use the following class to define a log table for your Azure cloud application. (You need to create the empty table first with something like Azure Storage Explorer. Note that Azure table names need to be lowercase or strange things might happen!)
The constructor defines the table name “log”, the account credentials to use (here as a static variable ABB, and whether to use https in connecting to the table (in this case false).
The second part of the class definition defines the structure of the table row, including the partition and row keys. In this case the partition key is the type of log message (error, warning, etc) and the row key is the timestamp of the message (in descending order). The message column contains the actual log message.
Note that the partition key and row key are always required for each table and together form the primary key for that row.
internal class LogTable : TableBase<LogTable.TableContext>
{
public LogTable() : base((baseAddress, credentials) => new TableContext("log", baseAddress, credentials), AccountCredentials.ABB, false) { }
public class Row : TableServiceEntity
{
public Row(string message, LogType type)
{
PartitionKey = type.ToString();
RowKey = (DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks).ToString();
Message = message;
}
public Row()
{
}
public string Message { get; set; }
}
public class TableContext : ContextBase<Row>
{
public TableContext(string tableName, string baseAddress, StorageCredentials credentials) : base(tableName, baseAddress, credentials) { }
}
public static void AddMessage(string message, LogType type = LogType.Error)
{
try {
var context = new LogTable().Context;
context.Add(new Row(message, type));
context.SaveAsync();
}
catch {
}
}
}
Adding a new log message
LogTable.AddMessage(“some message”);
LogTable.AddMessage(“some message”, LogType.Warning);
Getting a list of all log messages
var logMessages = new LogTable().ReadOnlyContext.Query.Select(r => r.Message);
0 comments:
Post a Comment