Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CloudWatch Logs用のクラスに差し替える #3

Merged
merged 3 commits into from Dec 23, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -6,6 +6,8 @@

<ItemGroup>

<PackageReference Include="Amazon.Lambda.CloudWatchLogsEvents" Version="1.0.0" />

<PackageReference Include="Amazon.Lambda.Core" Version="1.0.0" />
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="1.0.0" />

Expand Down
41 changes: 17 additions & 24 deletions ErrorNotificationLambda.Tests/FunctionTest.cs
@@ -1,40 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Xunit;
using Amazon.Lambda.Core;
using Amazon.Lambda.CloudWatchLogsEvents;
using Amazon.Lambda.TestUtilities;

using ErrorNotificationLambda;
using Xunit;

namespace ErrorNotificationLambda.Tests
{
public class FunctionTest : IClassFixture<LaunchSettingsFixture>
{
LaunchSettingsFixture _fixture;
LaunchSettingsFixture _fixture;

public FunctionTest(LaunchSettingsFixture fixture)
{
_fixture = fixture;
}
public FunctionTest(LaunchSettingsFixture fixture)
{
_fixture = fixture;
}

[Fact]
[Fact]
public async void TestErrorNotificationFunction()
{
var function = new Function();
var function = new Function();
var context = new TestLambdaContext();

var evnt = new LogEvent
{
Awslogs = new LogEvent.Log
{
Data = "H4sIAAAAAAAAAHWPwQqCQBCGX0Xm7EFtK+smZBEUgXoLCdMhFtKV3akI8d0bLYmibvPPN3wz00CJxmQnTO41whwWQRIctmEcB6sQbFC3CjW3XW8kxpOpP+OC22d1Wml1qZkQGtoMsScxaczKN3plG8zlaHIta5KqWsozoTYw3/djzwhpLwivWFGHGpAFe7DL68JlBUk+l7KSN7tCOEJ4M3/qOI49vMHj+zCKdlFqLaU2ZHV2a4Ct/an0/ivdX8oYc1UVX860fQDQiMdxRQEAAA=="
}
};
var evnt = new CloudWatchLogsEvent()
{
Awslogs = new CloudWatchLogsEvent.Log
{
EncodedData = "H4sIAAAAAAAAAHWPwQqCQBCGX0Xm7EFtK+smZBEUgXoLCdMhFtKV3akI8d0bLYmibvPPN3wz00CJxmQnTO41whwWQRIctmEcB6sQbFC3CjW3XW8kxpOpP+OC22d1Wml1qZkQGtoMsScxaczKN3plG8zlaHIta5KqWsozoTYw3/djzwhpLwivWFGHGpAFe7DL68JlBUk+l7KSN7tCOEJ4M3/qOI49vMHj+zCKdlFqLaU2ZHV2a4Ct/an0/ivdX8oYc1UVX860fQDQiMdxRQEAAA=="
}
};

var notification = await function.FunctionHandler(evnt, context);
var notification = await function.FunctionHandler(evnt, context);

Assert.True(notification);
}
Expand Down
52 changes: 26 additions & 26 deletions ErrorNotificationLambda.Tests/LaunchSettingsFixture.cs
Expand Up @@ -9,33 +9,33 @@

namespace ErrorNotificationLambda.Tests
{
public class LaunchSettingsFixture : IDisposable
{
public LaunchSettingsFixture()
{
using (var file = File.OpenText("Properties" + Path.DirectorySeparatorChar + "launchSettings.json"))
{
var reader = new JsonTextReader(file);
var jObject = JObject.Load(reader);
public class LaunchSettingsFixture : IDisposable
{
public LaunchSettingsFixture()
{
using (var file = File.OpenText("Properties" + Path.DirectorySeparatorChar + "launchSettings.json"))
{
var reader = new JsonTextReader(file);
var jObject = JObject.Load(reader);

var variables = jObject
.GetValue("profiles")
.SelectMany(profiles => profiles.Children())
.SelectMany(profile => profile.Children<JProperty>())
.Where(prop => prop.Name == "environmentVariables")
.SelectMany(prop => prop.Value.Children<JProperty>())
.ToList();
var variables = jObject
.GetValue("profiles")
.SelectMany(profiles => profiles.Children())
.SelectMany(profile => profile.Children<JProperty>())
.Where(prop => prop.Name == "environmentVariables")
.SelectMany(prop => prop.Value.Children<JProperty>())
.ToList();

foreach (var variable in variables)
{
Environment.SetEnvironmentVariable(variable.Name, variable.Value.ToString());
}
}
}
foreach (var variable in variables)
{
Environment.SetEnvironmentVariable(variable.Name, variable.Value.ToString());
}
}
}

public void Dispose()
{
// ... clean up
}
}
public void Dispose()
{
// ... clean up
}
}
}
1 change: 1 addition & 0 deletions ErrorNotificationLambda/ErrorNotificationLambda.csproj
Expand Up @@ -13,6 +13,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Amazon.Lambda.CloudWatchLogsEvents" Version="1.0.0" />
<PackageReference Include="Amazon.Lambda.Core" Version="1.0.0" />
<PackageReference Include="Amazon.Lambda.Serialization.Json" Version="1.1.0" />
</ItemGroup>
Expand Down
129 changes: 47 additions & 82 deletions ErrorNotificationLambda/Function.cs
@@ -1,110 +1,75 @@
using Amazon.Lambda.CloudWatchLogsEvents;
using Amazon.Lambda.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
using System.IO;
using System.IO.Compression;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using Amazon.Lambda.Core;
using System.Threading.Tasks;

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace ErrorNotificationLambda
{
public class Function
{

/// <summary>
/// <summary>
/// Notify contents waritten out on CloudWatch Logs
/// </summary>
/// <param name="logEvent"></param>
/// <param name="context"></param>
/// <returns></returns>
public async Task<bool> FunctionHandler(LogEvent logEvent, ILambdaContext context)
{
var slackWebhookUrl = Environment.GetEnvironmentVariable("SLACK_WEBHOOK_URL");
var cloudWatchLogGroupUrl = Environment.GetEnvironmentVariable("CLOUDWATCH_LOG_GROUP_URL");
var cloudWatchMetricsUrl = Environment.GetEnvironmentVariable("CLOUDWATCH_METRICS_URL");
/// </summary>
/// <param name="logEvent"></param>
/// <param name="context"></param>
/// <returns></returns>
public async Task<bool> FunctionHandler(CloudWatchLogsEvent logEvent, ILambdaContext context)
{
var slackWebhookUrl = Environment.GetEnvironmentVariable("SLACK_WEBHOOK_URL");
var cloudWatchLogGroupUrl = Environment.GetEnvironmentVariable("CLOUDWATCH_LOG_GROUP_URL");
var cloudWatchMetricsUrl = Environment.GetEnvironmentVariable("CLOUDWATCH_METRICS_URL");

var payload = new
{
channel = "dev",
username = "CloudWatch Notification",
text = $"{Decode(logEvent.Awslogs.Data)}"+ Environment.NewLine +
var payload = new
{
channel = "dev",
username = "CloudWatch Notification",
text = $"{GetMessage(logEvent.Awslogs.DecodeData())}" + Environment.NewLine +
$"Logs: <{cloudWatchLogGroupUrl}|Click here>" + Environment.NewLine +
$"Metrics: <{cloudWatchMetricsUrl}|Click here>",
};

var jsonString = JsonConvert.SerializeObject(payload);

var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "payload", jsonString}
});
};

try
{
using (var client = new HttpClient())
{
await client.PostAsync(slackWebhookUrl, content);
}
}
catch (Exception e)
{
context.Logger.LogLine("error!!!!" + Environment.NewLine + $"{e.Message}" + Environment.NewLine + $"{e.StackTrace}");
throw;
}

return true;
}
var jsonString = JsonConvert.SerializeObject(payload);

private string Decode(string encodedString)
{
var decodedString = "";

byte[] data = Convert.FromBase64String(encodedString);
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "payload", jsonString}
});

using (GZipStream stream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress))
try
{
const int size = 4096;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
using (var client = new HttpClient())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);

var messages = JObject.Parse(Encoding.UTF8.GetString(memory.ToArray())).GetValue("logEvents");
foreach (var item in messages)
{
decodedString += item["message"].Value<string>() + Environment.NewLine;
}
await client.PostAsync(slackWebhookUrl, content);
}
}
catch (Exception e)
{
context.Logger.LogLine("error!!!!" + Environment.NewLine + $"{e.Message}" + Environment.NewLine + $"{e.StackTrace}");
throw;
}

return decodedString;
return true;
}

private static string GetMessage(string decodedData)
{
string extractedMessage = "";
var messages = JObject.Parse(decodedData).GetValue("logEvents");
foreach (var item in messages)
{
extractedMessage += item["message"].Value<string>() + Environment.NewLine;
}
return extractedMessage;
}
}

public class LogEvent
{
public Log Awslogs { get; set; }
public class Log
{
public string Data { get; set; }
}
}
}