Skip to content

Instantly share code, notes, and snippets.

@kraigspear
Last active May 18, 2018 08:12
Show Gist options
  • Save kraigspear/436404913ab0565cb92500b4daeb2d75 to your computer and use it in GitHub Desktop.
Save kraigspear/436404913ab0565cb92500b4daeb2d75 to your computer and use it in GitHub Desktop.
Fetching Logs from CosmosDB
public static class HttpTrigger
{
[FunctionName("HttpTrigger")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string maxCountStr = req.GetQueryParameterDictionary().FirstOrDefault(q => string.Compare(q.Key, "max", true) == 0).Value;
int maxCount = 200;
if (maxCountStr != null)
{
int.TryParse(maxCountStr, out maxCount);
}
var logger = new Logger();
var logs = logger.Fetch(maxCount);
return (ActionResult)new OkObjectResult(logs);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;
namespace LoggerQuery
{
public sealed class Logger
{
readonly Uri Uri = new Uri("");
const string AuthKey = "";
readonly DocumentClient client;
public Logger()
{
client = new DocumentClient(Uri, AuthKey);
}
public IList<Log> Fetch(int maxCount = 200 )
{
var feedOptions = new FeedOptions {
EnableCrossPartitionQuery = true,
};
var logFromSQL = client.CreateDocumentQuery<Log>(DocumentURI, feedOptions);
var sortedLogs = (from l in logFromSQL
orderby l.Time descending
select l).Take(maxCount);
return sortedLogs.ToList();
}
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);
}
}
}
@kraigspear
Copy link
Author

Simple Azure function to retrieve the last 'n' logs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment