Last active
December 3, 2015 04:07
-
-
Save NickBranstein/3b423d3dd51e2c57a3e1 to your computer and use it in GitHub Desktop.
NLog Slack Target
This file contains hidden or 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 Bootstrap | |
| { | |
| private static void BootstrapNLog() | |
| { | |
| var config = new LoggingConfiguration(); | |
| var slackTarget = new SlackTarget(); | |
| config.AddTarget("slack", slackTarget); | |
| config.LoggingRules.Add(new LoggingRule("*", LogLevel.Warn, slackTarget)); | |
| LogManager.Configuration = config; | |
| } | |
| } |
This file contains hidden or 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 RequestHelper | |
| { | |
| public static string MakeJsonPost(string url, string json) | |
| { | |
| var httpClient = new HttpClient(); | |
| httpClient.DefaultRequestHeaders.ExpectContinue = false; | |
| httpClient.DefaultRequestHeaders.ConnectionClose = true; | |
| var stringContent = new StringContent(json); | |
| var response = httpClient.PostAsync(url, stringContent).Result; | |
| try | |
| { | |
| response.EnsureSuccessStatusCode(); | |
| } | |
| catch (Exception) | |
| { | |
| throw; | |
| } | |
| return response.Content.ReadAsStringAsync().Result; | |
| } | |
| } |
This file contains hidden or 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 class SlackPostModel | |
| { | |
| [JsonProperty("text")] | |
| public string Text { get; set; } | |
| } |
This file contains hidden or 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
| [Target("Slack")] | |
| public sealed class SlackTarget : TargetWithLayout | |
| { | |
| protected override void Write(LogEventInfo logEvent) | |
| { | |
| var logMessage = Layout.Render(logEvent); | |
| var json = JsonConvert.SerializeObject(new SlackPostModel() {Text = logMessage}); | |
| RequestHelper.MakeJsonPost(ConfigurationManager.AppSettings["Slack.HangfireUrl"], json); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment