Last active
May 18, 2018 08:12
-
-
Save kraigspear/436404913ab0565cb92500b4daeb2d75 to your computer and use it in GitHub Desktop.
Fetching Logs from CosmosDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple Azure function to retrieve the last 'n' logs.