Skip to content

Instantly share code, notes, and snippets.

@kraigspear
Last active May 18, 2018 08:06
Show Gist options
  • Save kraigspear/c751bbbaeb9d29471e4b94c80178b4e9 to your computer and use it in GitHub Desktop.
Save kraigspear/c751bbbaeb9d29471e4b94c80178b4e9 to your computer and use it in GitHub Desktop.
Azure Logging to Cosmos DB
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using System.Threading.Tasks;
namespace Logger
{
public static class HttpTrigger
{
[FunctionName("HttpTrigger")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string requestBody = new StreamReader(req.Body).ReadToEnd();
var logThis = JsonConvert.DeserializeObject<Log>(requestBody);
await new Logger().Add(logThis);
return (ActionResult)new OkResult();
}
}
}
// Add to the Log on Cosmos DB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;
namespace Logger
{
public sealed class Logger
{
readonly Uri Uri = new Uri(""); //Cosmos DB Url
const string PrimaryKey = ""; // Primary key to access Cosmos DB
readonly DocumentClient client;
public Logger()
{
client = new DocumentClient(Uri, PrimaryKey);
}
public async Task Add(Log log)
{
if (log == null)
throw new ArgumentNullException(nameof(log));
await client.CreateDocumentAsync(DocumentURI, log);
}
Uri DocumentURI
{
get => UriFactory.CreateDocumentCollectionUri("Log", "Log");
}
}
public sealed class Log
{
public DateTime Time { get; set; }
public string DeviceID { get; set; }
public string Level { get; set; }
public string SourceFile { get; set; }
public int LineNumber { get; set; }
public string Column { get; set; }
public string FunctionName { get; set; }
public string Message { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment