Skip to content

Instantly share code, notes, and snippets.

@the9ball
Last active August 8, 2018 09:00
Show Gist options
  • Select an option

  • Save the9ball/b9cefaaa2c80af319fc4d47a4a3f4fee to your computer and use it in GitHub Desktop.

Select an option

Save the9ball/b9cefaaa2c80af319fc4d47a4a3f4fee to your computer and use it in GitHub Desktop.
AWS Cloudwatch Logs からログを全部取ってくるやつ @ LinqPad
readonly RegionEndpoint Region = RegionEndpoint.APNortheast1;
readonly AWSCredentials Credentials = new BasicAWSCredentials();
const string LogGroupName = "";
const string LogStreamName = "";
async Task Main()
{
using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(30))) // 念のため
using (var client = new AmazonCloudWatchLogsClient(Credentials, Region))
{
var ct = cts.Token;
string nextToken = null;
while (!ct.IsCancellationRequested)
{
var (body, nt, endOfLog) = await ReadAsync(client, nextToken, ct);
body.Dump();
if (endOfLog) break;
nextToken = nt;
}
}
"=== finish ===".Dump();
}
async Task<(string body, string nextToken, bool endOfLog)> ReadAsync(AmazonCloudWatchLogsClient client, string nextToken, CancellationToken ct)
{
// https://docs.aws.amazon.com/ja_jp/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html
var request = new GetLogEventsRequest
{
LogGroupName = LogGroupName,
LogStreamName = LogStreamName,
NextToken = nextToken,
StartFromHead = nextToken == null, // nullなら先頭からということにする
};
var response = await client.GetLogEventsAsync(request, ct);
var body = string.Join("\n", response.Events.Select(x => $"{x.Timestamp} {x.Message}"));
var endOfLog = response.NextForwardToken == nextToken; // 終端だったら渡したトークンと同じものが返ってくるらしい
return (body, response.NextForwardToken, endOfLog);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment