• R/O
  • SSH
  • HTTPS

ewatch: Commit


Commit MetaInfo

Revision111 (tree)
Zeit2020-07-02 17:16:14
Autorbananajinn

Log Message

* メール送信でエラーの場合は重要度=緊急で送信する
* EWatch.config.json に General.name を追加

Ändern Zusammenfassung

Diff

--- trunk/EWatch/EWatch/Actions/ActionExecute.cs (revision 110)
+++ trunk/EWatch/EWatch/Actions/ActionExecute.cs (revision 111)
@@ -37,6 +37,7 @@
3737 {
3838 string timestampString = (data.TimeStamp ?? DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss.fff");
3939 string cmdLine = CommandLine
40+ .Replace("$name", data.Name)
4041 .Replace("$timestamp", timestampString)
4142 .Replace("$hostname", data.HostName)
4243 .Replace("$source", data.Source)
--- trunk/EWatch/EWatch/Actions/ActionMantis.cs (revision 110)
+++ trunk/EWatch/EWatch/Actions/ActionMantis.cs (revision 111)
@@ -146,6 +146,9 @@
146146 result.AppendFormat("level:\t{0}\r\n", data.Level);
147147 result.AppendFormat("code:\t{0}\r\n", data.Code);
148148 }
149+ if(!Util.IsNullOrEmpty(data.Name)){
150+ result.AppendFormat("name:\t{0}\r\n", data.Name);
151+ }
149152 if(!Util.IsNullOrEmpty(data.HostName)){
150153 result.AppendFormat("host:\t{0}\r\n", data.HostName);
151154 }
--- trunk/EWatch/EWatch/Actions/ActionRedmine.cs (revision 110)
+++ trunk/EWatch/EWatch/Actions/ActionRedmine.cs (revision 111)
@@ -33,11 +33,13 @@
3333
3434 public override void Execute(LogData data)
3535 {
36- lock(lockObject){
36+ lock (lockObject) {
3737 var subject = string.Format("[{0}] {1}", data.HostName, DeleteTimestamp(data.Message));
38- if(subject.Length > 255)
38+ if (!string.IsNullOrEmpty(data.Name))
39+ subject = string.Format("[{0}]{1}", data.Name, subject);
40+ if (subject.Length > 255)
3941 subject = subject.Substring(0, 255);
40- if(!IsIssued(subject)){
42+ if (!IsIssued(subject)) {
4143 SendIssue(subject, data);
4244 }
4345 }
@@ -45,19 +47,19 @@
4547
4648 public override bool Validate()
4749 {
48- if(Util.IsNullOrEmpty(BaseUrl)){
50+ if (Util.IsNullOrEmpty(BaseUrl)) {
4951 log.Error("BaseUrl is not specified.");
5052 return false;
5153 }
52- if(Util.IsNullOrEmpty(APIKey)){
54+ if (Util.IsNullOrEmpty(APIKey)) {
5355 log.Error("APIKey is not specified.");
5456 return false;
5557 }
56- if(Util.IsNullOrEmpty(ProjectID)){
58+ if (Util.IsNullOrEmpty(ProjectID)) {
5759 log.Error("ProjectID is not specified.");
5860 return false;
5961 }
60- if(Util.IsNullOrEmpty(TrackerID)){
62+ if (Util.IsNullOrEmpty(TrackerID)) {
6163 log.Error("TrackerID is not specified.");
6264 return false;
6365 }
@@ -82,10 +84,10 @@
8284 var json = Request("/issues.json?author_id=me&status_id=open&sort=created_on:desc&limit=100", null, null);
8385 var jo = JObject.Parse(json);
8486 var jarray = jo["issues"] as JArray;
85- if(jarray != null){
86- foreach(var issue in jarray){
87+ if (jarray != null) {
88+ foreach (var issue in jarray) {
8789 var s = issue["subject"].ToString();
88- if(subject.Equals(s)){
90+ if (subject.Equals(s)) {
8991 return true;
9092 }
9193 }
@@ -113,12 +115,12 @@
113115 var req = (HttpWebRequest)WebRequest.Create(url);
114116 req.Headers.Add("X-Redmine-API-Key", APIKey);
115117 req.Method = string.IsNullOrEmpty(postData) ? "GET" : "POST";
116- if(!string.IsNullOrEmpty(contentType))
118+ if (!string.IsNullOrEmpty(contentType))
117119 req.ContentType = contentType;
118120 req.ContentLength = data.Length;
119121
120- if(!Util.IsNullOrEmpty(data)){
121- using(Stream s = req.GetRequestStream()){
122+ if (!Util.IsNullOrEmpty(data)) {
123+ using (Stream s = req.GetRequestStream()) {
122124 s.Write(data, 0, data.Length);
123125 }
124126 }
@@ -125,7 +127,7 @@
125127
126128 string result = null;
127129 WebResponse res = req.GetResponse();
128- using(var sr = new StreamReader(res.GetResponseStream())){
130+ using (var sr = new StreamReader(res.GetResponseStream())) {
129131 result = sr.ReadToEnd();
130132 }
131133 return result;
@@ -135,14 +137,17 @@
135137 {
136138 var result = new StringBuilder();
137139 result.AppendFormat("Time:\t{0}\r\n", data.TimeStamp.Value.ToString("yyyy-MM-dd HH:mm:ss.fff"));
138- if(!Util.IsNullOrEmpty(data.Level)){
140+ if (!Util.IsNullOrEmpty(data.Level)) {
139141 result.AppendFormat("level:\t{0}\r\n", data.Level);
140142 result.AppendFormat("code:\t{0}\r\n", data.Code);
141143 }
142- if(!Util.IsNullOrEmpty(data.HostName)){
144+ if (!Util.IsNullOrEmpty(data.Name)) {
145+ result.AppendFormat("name:\t{0}\r\n", data.Name);
146+ }
147+ if (!Util.IsNullOrEmpty(data.HostName)) {
143148 result.AppendFormat("host:\t{0}\r\n", data.HostName);
144149 }
145- if(!Util.IsNullOrEmpty(data.Source)){
150+ if (!Util.IsNullOrEmpty(data.Source)) {
146151 result.AppendFormat("source:\t{0}\r\n", data.Source);
147152 }
148153 result.AppendFormat("{0}\r\n", data.Message);
--- trunk/EWatch/EWatch/Actions/ActionSlack.cs (revision 110)
+++ trunk/EWatch/EWatch/Actions/ActionSlack.cs (revision 111)
@@ -57,12 +57,12 @@
5757
5858 public override bool Validate()
5959 {
60- if(Util.IsNullOrEmpty(URL)){
60+ if (Util.IsNullOrEmpty(URL)) {
6161 log.Error("Token is not specified.");
6262 return false;
6363 }
64- if(!Util.IsNullOrEmpty(Attachments)){
65- if(JsonUtil.Parse(Attachments) == null){
64+ if (!Util.IsNullOrEmpty(Attachments)) {
65+ if (JsonUtil.Parse(Attachments) == null) {
6666 log.Error("Attachments is invalid.");
6767 return false;
6868 }
@@ -74,30 +74,34 @@
7474 {
7575 var text = new StringBuilder();
7676 text.AppendFormat("Time: {0}\n", data.TimeStamp.Value.ToString("yyyy-MM-dd HH:mm:ss.fff"));
77- if(!Util.IsNullOrEmpty(data.Level)){
77+ if (!Util.IsNullOrEmpty(data.Level)) {
7878 text.AppendFormat("level: {0}\n", data.Level);
7979 text.AppendFormat("code: {0}\n", data.Code);
8080 }
81- if(!Util.IsNullOrEmpty(data.HostName)){
81+ if (!Util.IsNullOrEmpty(data.Name)) {
82+ text.AppendFormat("name: {0}\n", data.Name);
83+ }
84+ if (!Util.IsNullOrEmpty(data.HostName)) {
8285 text.AppendFormat("host: {0}\n", data.HostName);
8386 }
84- if(!Util.IsNullOrEmpty(data.Source)){
87+ if (!Util.IsNullOrEmpty(data.Source)) {
8588 text.AppendFormat("source: {0}\n", data.Source);
8689 }
8790 text.AppendFormat("{0}\n", data.Message);
88- Send(string.Concat("payload=", HttpUtility.UrlEncode(GetJSON(
89- string.Format("[{0}] {1}", data.HostName, GetSubject(data.Message)),
90- text.ToString()))));
91+ var subject = string.Format("[{0}] {1}", data.HostName, GetSubject(data.Message));
92+ if (!Util.IsNullOrEmpty(data.Name))
93+ subject = string.Format("[{0}]{1}", data.Name, subject);
94+ Send(string.Concat("payload=", HttpUtility.UrlEncode(GetJSON(subject, text.ToString()))));
9195 }
9296
9397 private string GetSubject(string value)
9498 {
95- if(!string.IsNullOrEmpty(value)){
99+ if (!string.IsNullOrEmpty(value)) {
96100 // 改行があればそこで区切る
97101 var array = value.Split('\n');
98102 value = array[0];
99103 // 255文字以上ならそこで区切る
100- if(value.Length > 255)
104+ if (value.Length > 255)
101105 value = value.Substring(0, 255);
102106 }
103107 return value;
@@ -106,25 +110,25 @@
106110 private string GetJSON(string title, string text)
107111 {
108112 var jo = new JObject();
109- if(!Util.IsNullOrEmpty(Attachments)){
113+ if (!Util.IsNullOrEmpty(Attachments)) {
110114 var attachment = JsonUtil.Parse(Attachments) as JObject;
111115 attachment["title"] = title;
112116 attachment["text"] = text;
113117 attachment["fallback"] = title;
114- jo["attachments"] = new JArray(attachment);;
115- }
116- else {
118+ jo["attachments"] = new JArray(attachment);
119+ ;
120+ } else {
117121 jo["text"] = string.Join("\n", title, text);
118122 }
119- if(!Util.IsNullOrEmpty(UserName)){
123+ if (!Util.IsNullOrEmpty(UserName)) {
120124 jo["as_user"] = "0";
121125 jo["username"] = UserName;
122126 }
123- if(!Util.IsNullOrEmpty(IconEmoji)){
127+ if (!Util.IsNullOrEmpty(IconEmoji)) {
124128 jo["as_user"] = "0";
125129 jo["icon_emoji"] = IconEmoji;
126130 }
127- if(!Util.IsNullOrEmpty(Channel)){
131+ if (!Util.IsNullOrEmpty(Channel)) {
128132 jo["channel"] = Channel;
129133 }
130134 return jo.ToString();
@@ -138,13 +142,13 @@
138142 req.ContentType = "application/x-www-form-urlencoded";
139143 req.ContentLength = data.Length;
140144
141- using(Stream s = req.GetRequestStream()){
145+ using (Stream s = req.GetRequestStream()) {
142146 s.Write(data, 0, data.Length);
143147 }
144148
145149 string result = null;
146150 WebResponse res = req.GetResponse();
147- using(var sr = new StreamReader(res.GetResponseStream())){
151+ using (var sr = new StreamReader(res.GetResponseStream())) {
148152 result = sr.ReadToEnd();
149153 }
150154 return result;
--- trunk/EWatch/EWatch/Actions/ActionSmtp.cs (revision 110)
+++ trunk/EWatch/EWatch/Actions/ActionSmtp.cs (revision 111)
@@ -35,7 +35,7 @@
3535 string[] hostAndPort = value.Split(new char[]{ ':' });
3636 _serverHost = hostAndPort[0];
3737 _serverPort = 25;
38- if(hostAndPort.Length >= 2){
38+ if (hostAndPort.Length >= 2) {
3939 int.TryParse(hostAndPort[1], out _serverPort);
4040 }
4141 }
@@ -55,15 +55,15 @@
5555
5656 public override bool Validate()
5757 {
58- if(Util.IsNullOrEmpty(_serverHost)){
58+ if (Util.IsNullOrEmpty(_serverHost)) {
5959 log.Error("ServerHost is not specified.");
6060 return false;
6161 }
62- if(Util.IsNullOrEmpty(FromAddress)){
62+ if (Util.IsNullOrEmpty(FromAddress)) {
6363 log.Error("FromAddress is not specified.");
6464 return false;
6565 }
66- if(Util.IsNullOrEmpty(ToAddress)){
66+ if (Util.IsNullOrEmpty(ToAddress)) {
6767 log.Error("ToAddress is not specified.");
6868 return false;
6969 }
@@ -72,46 +72,54 @@
7272
7373 public override void Execute(LogData data)
7474 {
75- lock(lockObject){
75+ lock (lockObject) {
7676 StringBuilder body = new StringBuilder();
7777 body.AppendFormat("Time: {0}\r\n", data.TimeStamp.Value.ToString("yyyy-MM-dd HH:mm:ss.fff"));
78- if(!Util.IsNullOrEmpty(data.Level)){
78+ if (!Util.IsNullOrEmpty(data.Level)) {
7979 body.AppendFormat("level: {0}\r\n", data.Level);
8080 body.AppendFormat("code: {0}\r\n", data.Code);
8181 }
82- if(!Util.IsNullOrEmpty(data.HostName)){
82+ if (!Util.IsNullOrEmpty(data.Name)) {
83+ body.AppendFormat("name: {0}\r\n", data.Name);
84+ }
85+ if (!Util.IsNullOrEmpty(data.HostName)) {
8386 body.AppendFormat("host: {0}\r\n", data.HostName);
8487 }
85- if(!Util.IsNullOrEmpty(data.Source)){
88+ if (!Util.IsNullOrEmpty(data.Source)) {
8689 body.AppendFormat("source: {0}\r\n", data.Source);
8790 }
8891 body.AppendFormat("{0}\r\n", data.Message);
89- Send(GetSubject(string.Format("[{0}] {1}", data.HostName, data.Message)), body.ToString());
92+ var subject = string.Format("[{0}] {1}", data.HostName, data.Message);
93+ if (!string.IsNullOrEmpty(data.Name))
94+ subject = string.Format("[{0}]{1}", data.Name, subject);
95+ Send(GetSubject(subject),
96+ body.ToString(),
97+ data.Level == "E");
9098 }
9199 }
92100
93101 private string GetSubject(string value)
94102 {
95- if(!string.IsNullOrEmpty(value)){
103+ if (!string.IsNullOrEmpty(value)) {
96104 // 改行があればそこで区切る
97105 var array = value.Split('\n');
98106 value = array[0];
99107 // 76文字以上ならそこで区切る
100- if(value.Length > 76)
108+ if (value.Length > 76)
101109 value = value.Substring(0, 76);
102110 }
103111 return value;
104112 }
105113
106- private void Send(string subject, string body)
114+ private void Send(string subject, string body, bool urgent)
107115 {
108- using(var sender = new EMailSender(_serverHost, _serverPort,
109- Protection, AuthMethod,
110- UserID, Password, null)){
116+ using (var sender = new EMailSender(_serverHost, _serverPort,
117+ Protection, AuthMethod,
118+ UserID, Password, null)) {
111119 sender.Send(subject, body,
112- new MailAddress(FromAddress),
113- ToAddress.Split(',').Select(x => new MailAddress(x)).ToArray(),
114- null, null);
120+ new MailAddress(FromAddress),
121+ ToAddress.Split(',').Select(x => new MailAddress(x)).ToArray(),
122+ null, null, urgent);
115123 }
116124 }
117125 }
--- trunk/EWatch/EWatch/Actions/ActionTeams.cs (revision 110)
+++ trunk/EWatch/EWatch/Actions/ActionTeams.cs (revision 111)
@@ -71,7 +71,10 @@
7171 jo["themeColor"] = ThemeColor;
7272 }
7373 jo["summary"] = string.Format("notification from {0}", data.HostName);
74- jo["title"] = string.Format("[{0}] {1}", data.HostName, GetSubject(data.Message));
74+ var subject = string.Format("[{0}] {1}", data.HostName, GetSubject(data.Message));
75+ if (!string.IsNullOrEmpty(data.Name))
76+ subject = string.Format("[{0}]{1}", data.Name, subject);
77+ jo["title"] = subject;
7578 jo["sections"] = new JArray(GetSection(data));
7679 return jo.ToString();
7780 }
@@ -83,6 +86,7 @@
8386 GetFact("Time", data.TimeStamp.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")),
8487 GetFact("Level", data.Level),
8588 GetFact("Code", data.Code.ToString()),
89+ GetFact("Name", data.Name),
8690 GetFact("Host", data.HostName),
8791 GetFact("Source", data.Source)
8892 );
@@ -94,7 +98,7 @@
9498 {
9599 dynamic result = new JObject();
96100 result.name = name;
97- result.value = value;
101+ result.value = value ?? string.Empty;
98102 return result;
99103 }
100104
--- trunk/EWatch/EWatch/Configuration.cs (revision 110)
+++ trunk/EWatch/EWatch/Configuration.cs (revision 111)
@@ -78,6 +78,7 @@
7878 value);
7979 }
8080 }
81+ public GeneralConfiguration General { get; private set; }
8182 public ServerConfiguration Server { get; private set; }
8283
8384 public Configuration() : this(true)
@@ -136,6 +137,15 @@
136137 return result;
137138 }
138139
140+ private void GetGeneralSettings(object jobject)
141+ {
142+ if(jobject != null){
143+ General = new GeneralConfiguration {
144+ Name = JsonUtil.GetString(jobject, "name")
145+ };
146+ }
147+ }
148+
139149 private void GetActions(object jobject)
140150 {
141151 if(jobject != null){
@@ -156,6 +166,8 @@
156166 private void ParseJson(string json)
157167 {
158168 object j = JsonUtil.Parse(json);
169+ object general = JsonUtil.GetObject(j, "General");
170+ GetGeneralSettings(general);
159171 object actions = JsonUtil.GetObject(j, "Actions");
160172 if(actions == null)
161173 throw new InvalidDataException();
@@ -273,6 +285,10 @@
273285 JsonUtil.Get<ServerConfiguration>(json, Server);
274286 }
275287
288+ public class GeneralConfiguration
289+ {
290+ public string Name { get; set; }
291+ }
276292
277293 public class ServerConfiguration
278294 {
--- trunk/EWatch/EWatch/Models/LogData.cs (revision 110)
+++ trunk/EWatch/EWatch/Models/LogData.cs (revision 111)
@@ -16,6 +16,7 @@
1616 /// </summary>
1717 public class LogData
1818 {
19+ public string Name { get; set; }
1920 public string HostName { get; set; }
2021 public DateTime? TimeStamp { get; set; }
2122 public string Source { get; set; }
--- trunk/EWatch/EWatch/Properties/AssemblyInfo.cs (revision 110)
+++ trunk/EWatch/EWatch/Properties/AssemblyInfo.cs (revision 111)
@@ -1,27 +1,23 @@
1-#region Using directives
2-
1+#region Using directives
32 using System;
43 using System.Reflection;
54 using System.Runtime.InteropServices;
65
76 #endregion
8-
97 // General Information about an assembly is controlled through the following
108 // set of attributes. Change these attribute values to modify the information
119 // associated with an assembly.
12-[assembly: AssemblyTitle("EWatch")]
13-[assembly: AssemblyDescription("")]
14-[assembly: AssemblyConfiguration("")]
15-[assembly: AssemblyCompany("")]
16-[assembly: AssemblyProduct("EWatch")]
17-[assembly: AssemblyCopyright("Copyright 2013-2018 BananaJinn")]
18-[assembly: AssemblyTrademark("")]
19-[assembly: AssemblyCulture("")]
20-
10+[assembly: AssemblyTitle ("EWatch")]
11+[assembly: AssemblyDescription ("")]
12+[assembly: AssemblyConfiguration ("")]
13+[assembly: AssemblyCompany ("")]
14+[assembly: AssemblyProduct ("EWatch")]
15+[assembly: AssemblyCopyright ("Copyright 2013-2018 BananaJinn")]
16+[assembly: AssemblyTrademark ("")]
17+[assembly: AssemblyCulture ("")]
2118 // This sets the default COM visibility of types in the assembly to invisible.
2219 // If you need to expose a type to COM, use [ComVisible(true)] on that type.
23-[assembly: ComVisible(false)]
24-
20+[assembly: ComVisible (false)]
2521 // The assembly version has following format :
2622 //
2723 // Major.Minor.Build.Revision
@@ -28,6 +24,5 @@
2824 //
2925 // You can specify all the values or you can use the default the Revision and
3026 // Build Numbers by using the '*' as shown below:
31-[assembly: AssemblyVersion("1.0.30")]
32-
33-//[assembly: log4net.Config.XmlConfigurator(ConfigFile=@"Log4net.Config.xml", Watch=true)]
\ No newline at end of file
27+[assembly: AssemblyVersion ("1.0.30")]
28+//[assembly: log4net.Config.XmlConfigurator(ConfigFile=@"Log4net.Config.xml", Watch=true)]
--- trunk/EWatch/EWatch/Utils/EMailSender.cs (revision 110)
+++ trunk/EWatch/EWatch/Utils/EMailSender.cs (revision 111)
@@ -42,7 +42,7 @@
4242 }
4343
4444 public EMailSender(string server, int port, Protections protection, AuthenticateMethods authMethod,
45- string userId, string password, string userAgent)
45+ string userId, string password, string userAgent)
4646 {
4747 Server = server;
4848 Port = port;
@@ -54,10 +54,11 @@
5454 }
5555
5656 public void Send(string subject, string body,
57- MailAddress fromAddress,
58- MailAddress[] toAddresses,
59- MailAddress[] ccAddresses,
60- MailAddress[] bccAddresses)
57+ MailAddress fromAddress,
58+ MailAddress[] toAddresses,
59+ MailAddress[] ccAddresses,
60+ MailAddress[] bccAddresses,
61+ bool urgent)
6162 {
6263 Connect();
6364 SendMailFrom(fromAddress.Address);
@@ -65,23 +66,27 @@
6566 var headers = new List<string>();
6667
6768 headers.AddRange(CreateHeader("From", fromAddress));
68- if(toAddresses != null){
69+ if (toAddresses != null) {
6970 addresses.AddRange(toAddresses.Select(x => x.Address));
7071 headers.AddRange(CreateHeader("To", toAddresses));
7172 }
72- if(ccAddresses != null){
73+ if (ccAddresses != null) {
7374 addresses.AddRange(ccAddresses.Select(x => x.Address));
7475 headers.AddRange(CreateHeader("Cc", ccAddresses));
7576 }
76- if(bccAddresses != null){
77+ if (bccAddresses != null) {
7778 addresses.AddRange(bccAddresses.Select(x => x.Address));
7879 }
79- if(subject != null){
80+ if (subject != null) {
8081 headers.AddRange(CreateHeader("Subject", subject));
8182 }
8283 headers.AddRange(CreateHeader("Content-Type", "text/plain; charset=utf-8; format=flowed"));
8384 headers.AddRange(CreateHeader("Content-Transfer-Encoding", "8bit"));
8485 headers.AddRange(CreateHeader("User-Agent", UserAgent));
86+ if (urgent) {
87+ headers.AddRange(CreateHeader("Priority", "urgent"));
88+ headers.AddRange(CreateHeader("X-Priority", "1"));
89+ }
8590 headers.Add(string.Empty);
8691 headers.Add(string.Empty);
8792 SendRcptTo(addresses.ToArray());
@@ -93,19 +98,19 @@
9398
9499 private void Connect()
95100 {
96- if(!string.IsNullOrEmpty(DumpFile)){
101+ if (!string.IsNullOrEmpty(DumpFile)) {
97102 OpenDumpFile(DumpFile);
98103 return;
99104 }
100- if(!Connected){
105+ if (!Connected) {
101106 Connect(Server, Port, Protection == Protections.SslTls);
102107 Receive();
103108 SendEHlo();
104- if(Protection == Protections.StartTls){
109+ if (Protection == Protections.StartTls) {
105110 SendStartTls();
106111 SendEHlo();
107112 }
108- switch(AuthenticateMethod){
113+ switch (AuthenticateMethod) {
109114 case AuthenticateMethods.Plain:
110115 SendAuthPlain(UserID, UserID, Password);
111116 break;
@@ -126,17 +131,16 @@
126131 {
127132 var sb = new EMailStringBuilder();
128133 sb.Append(name).Append(": ");
129- var lastIndex = addresses.Length-1;
130- for(int index=0; index<addresses.Length; index++){
134+ var lastIndex = addresses.Length - 1;
135+ for (int index = 0; index < addresses.Length; index++) {
131136 var address = addresses[index];
132- if(!string.IsNullOrEmpty(address.DisplayName)){
137+ if (!string.IsNullOrEmpty(address.DisplayName)) {
133138 sb.Append(address.DisplayName);
134139 sb.Append(string.Concat(string.Format(" <{0}>", address.Address),
135- lastIndex == index ? string.Empty : ","));
136- }
137- else{
140+ lastIndex == index ? string.Empty : ","));
141+ } else {
138142 sb.Append(string.Concat(address.Address,
139- lastIndex == index ? string.Empty : ","));
143+ lastIndex == index ? string.Empty : ","));
140144 }
141145 }
142146 return sb.ToStrings();
@@ -145,7 +149,8 @@
145149 /// <summary>
146150 /// 接続保護モード
147151 /// </summary>
148- public enum Protections {
152+ public enum Protections
153+ {
149154 None,
150155 StartTls,
151156 SslTls,
@@ -154,7 +159,8 @@
154159 /// <summary>
155160 /// 認証モード
156161 /// </summary>
157- public enum AuthenticateMethods {
162+ public enum AuthenticateMethods
163+ {
158164 None,
159165 Plain,
160166 Login,
--- trunk/EWatch/EWatch/Watchers/EventLogWatcher.cs (revision 110)
+++ trunk/EWatch/EWatch/Watchers/EventLogWatcher.cs (revision 111)
@@ -20,14 +20,16 @@
2020 /// </summary>
2121 public class EventLogWatcher : BaseWatcher
2222 {
23+ private Configuration.GeneralConfiguration generalConf;
2324 private string name;
24-#if _WINDOWS
25+ #if _WINDOWS
2526 private EventBookmark bookmark;
2627 #endif
2728
28- public EventLogWatcher(string name, List<ActionTable> actionTable)
29+ public EventLogWatcher(Configuration.GeneralConfiguration generalConf, string name, List<ActionTable> actionTable)
2930 : base(actionTable)
3031 {
32+ this.generalConf = generalConf;
3133 this.name = name;
3234 }
3335
@@ -94,6 +96,7 @@
9496 }
9597 if (rec.TimeCreated > DateTime.Now.AddDays(-1)) {
9698 FindAndExecute(new LogData {
99+ Name = generalConf != null ? generalConf.Name : null,
97100 Code = rec.Id,
98101 HostName = rec.MachineName,
99102 Source = rec.ProviderName,
@@ -109,8 +112,7 @@
109112 {
110113 try {
111114 return rec.FormatDescription();
112- }
113- catch(Exception ex) {
115+ } catch (Exception ex) {
114116 log.Error("format error", ex);
115117 return "---";
116118 }
--- trunk/EWatch/EWatch/Watchers/FileWatcher.cs (revision 110)
+++ trunk/EWatch/EWatch/Watchers/FileWatcher.cs (revision 111)
@@ -23,13 +23,17 @@
2323 /// </summary>
2424 public class FileWatcher : BaseWatcher
2525 {
26+ private Configuration.GeneralConfiguration generalConf;
2627 private string path;
2728 private Encoding encoding;
2829 private long position = -1;
2930 private bool successRead = true;
3031
31- public FileWatcher(string path, Encoding encoding, List<ActionTable> actionTable) : base(actionTable)
32+ public FileWatcher(Configuration.GeneralConfiguration generalConf,
33+ string path, Encoding encoding, List<ActionTable> actionTable)
34+ : base(actionTable)
3235 {
36+ this.generalConf = generalConf;
3337 this.path = path;
3438 this.encoding = encoding;
3539 }
@@ -37,33 +41,34 @@
3741 public override void Watch()
3842 {
3943 try {
40- using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){
44+ using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
4145 fs.Seek(0, SeekOrigin.End);
42- if(position < 0){
46+ if (position < 0) {
4347 position = fs.Position;
44- }
45- else{
46- if(position > fs.Position){
48+ } else {
49+ if (position > fs.Position) {
4750 position = 0;
4851 }
4952 fs.Seek(position, SeekOrigin.Begin);
50- using(StreamReader sr = new StreamReader(fs, encoding)){
53+ using (StreamReader sr = new StreamReader(fs, encoding)) {
5154 string preReadLine = null;
52- while(!sr.EndOfStream || preReadLine != null){
55+ while (!sr.EndOfStream || preReadLine != null) {
5356 string line = preReadLine ?? sr.ReadLine();
5457 preReadLine = null;
5558 var data = new LogData {
59+ Name = generalConf != null ? generalConf.Name : null,
5660 TimeStamp = DateTime.Now,
5761 HostName = Environment.MachineName,
5862 Source = path,
5963 Message = line,
64+ Level = line.ToLower().Contains("error") ? "E" : "W"
6065 };
6166 var table = LogMatcher.Match(actionTable, data);
62- if(table != null) {
63- if(!string.IsNullOrEmpty(table.WhilePattern)){
67+ if (table != null) {
68+ if (!string.IsNullOrEmpty(table.WhilePattern)) {
6469 var lines = new List<string>();
6570 preReadLine = PreRead(sr, lines, table.WhilePattern, table.WhileMax, 500);
66- if(!Util.IsNullOrEmpty(lines)){
71+ if (!Util.IsNullOrEmpty(lines)) {
6772 data.Message = string.Join("\n", data.Message, string.Join("\n", lines));
6873 }
6974 }
@@ -75,9 +80,8 @@
7580 }
7681 }
7782 successRead = true;
78- }
79- catch(Exception ex){
80- if(successRead){
83+ } catch (Exception ex) {
84+ if (successRead) {
8185 log.WarnFormat("Read error : {0}({1})", ex.Message, path);
8286 successRead = false;
8387 }
@@ -90,10 +94,10 @@
9094 var timeout = DateTime.Now.AddMilliseconds(timeoutMilliSec);
9195 var count = 0;
9296
93- while(DateTime.Now.CompareTo(timeout) < 0){
94- while(!sr.EndOfStream && (max == null || count < max)){
97+ while (DateTime.Now.CompareTo(timeout) < 0) {
98+ while (!sr.EndOfStream && (max == null || count < max)) {
9599 var line = sr.ReadLine();
96- if(!regex.IsMatch(line)){
100+ if (!regex.IsMatch(line)) {
97101 return line;
98102 }
99103 buffer.Add(line);
--- trunk/EWatch/EWatch/Watchers/SyslogServer.cs (revision 110)
+++ trunk/EWatch/EWatch/Watchers/SyslogServer.cs (revision 111)
@@ -24,13 +24,17 @@
2424 /// </summary>
2525 public class SyslogServer : BaseWatcher
2626 {
27+ private Configuration.GeneralConfiguration generalConf;
2728 private bool stopRunning;
2829 private Thread listener;
2930 private int listenPort;
3031
31- public SyslogServer(string port, List<ActionTable> actionTable) : base(actionTable)
32+ public SyslogServer(Configuration.GeneralConfiguration generalConf,
33+ string port, List<ActionTable> actionTable)
34+ : base(actionTable)
3235 {
33- if(!int.TryParse(port, out listenPort)){
36+ this.generalConf = generalConf;
37+ if (!int.TryParse(port, out listenPort)) {
3438 listenPort = 514;
3539 }
3640 stopRunning = false;
@@ -55,22 +59,19 @@
5559 UdpClient udpListener = new UdpClient(listenPort);
5660 byte[] receiveData;
5761
58- while(!stopRunning){
62+ while (!stopRunning) {
5963 try {
6064 udpListener.Client.ReceiveTimeout = 1000;
6165 receiveData = udpListener.Receive(ref endPoint);
6266 string data = Encoding.UTF8.GetString(receiveData);
6367 HandleLog(data);
64- }
65- catch(SocketException) {
68+ } catch (SocketException) {
6669 continue;
67- }
68- catch(Exception ex) {
70+ } catch (Exception ex) {
6971 log.ErrorFormat("Receive error : {0}", ex.Message);
7072 }
7173 }
72- }
73- catch(Exception ex) {
74+ } catch (Exception ex) {
7475 log.ErrorFormat("abort : {0}", ex.Message);
7576 }
7677 }
@@ -79,18 +80,18 @@
7980 {
8081 data = data.Replace("\r", "").Replace("\n", "");
8182 Match match = Regex.Match(data, "<([0-9]+)>([A-Za-z]{3} [ 0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}) ([^ ]+) (.*)");
82- if(match != null && match.Groups.Count==5){
83+ if (match != null && match.Groups.Count == 5) {
8384 int priority;
8485 int.TryParse(match.Groups[1].Value, out priority);
85- FindAndExecute(new LogData{
86- TimeStamp = GetTimeStamp(match.Groups[2].Value),
87- HostName = match.Groups[3].Value,
88- Message = match.Groups[4].Value,
89- Level = GetLevel(priority % 8),
90- Source = GetFacilityName(priority / 8),
91- });
92- }
93- else{
86+ FindAndExecute(new LogData {
87+ Name = generalConf != null ? generalConf.Name : null,
88+ TimeStamp = GetTimeStamp(match.Groups[2].Value),
89+ HostName = match.Groups[3].Value,
90+ Message = match.Groups[4].Value,
91+ Level = GetLevel(priority % 8),
92+ Source = GetFacilityName(priority / 8),
93+ });
94+ } else {
9495 log.ErrorFormat("Invalid log received : {0}", data);
9596 }
9697 }
@@ -99,14 +100,15 @@
99100 {
100101 DateTime result = DateTime.Now;
101102 Match match = Regex.Match(dateString, "([A-Za-z]{3}) ([ 0-9]{2}) ([0-9]{2}:[0-9]{2}:[0-9]{2})");
102- if(match != null && match.Groups.Count==4){
103+ if (match != null && match.Groups.Count == 4) {
103104 int month, day;
104105 month = Util.GetMonthFromString(match.Groups[1].Value);
105- if(month == 0) month = DateTime.Now.Month;
106+ if (month == 0)
107+ month = DateTime.Now.Month;
106108 int.TryParse(match.Groups[2].Value, out day);
107109 result = DateTime.Parse(match.Groups[3].Value);
108110 result = new DateTime(result.Year, month, day, result.Hour, result.Minute, result.Second);
109- if(result.Month==12 && DateTime.Now.Month==1){
111+ if (result.Month == 12 && DateTime.Now.Month == 1) {
110112 result.AddYears(-1);
111113 }
112114 }
@@ -116,23 +118,23 @@
116118 private string GetLevel(int severity)
117119 {
118120 string result = null;
119- switch(severity){
120- case 0: /* EMERGENCY */
121- case 1: /* ALERT */
122- case 2: /* CRITICAL */
123- case 3: /* ERROR */
124- result = "E";
125- break;
126- case 4: /* WARNING */
127- result = "W";
128- break;
129- case 5: /* NOTICE */
130- case 6: /* INFORMATION */
131- result = "I";
132- break;
133- case 7: /* DEBUG */
134- result = "D";
135- break;
121+ switch (severity) {
122+ case 0: /* EMERGENCY */
123+ case 1: /* ALERT */
124+ case 2: /* CRITICAL */
125+ case 3: /* ERROR */
126+ result = "E";
127+ break;
128+ case 4: /* WARNING */
129+ result = "W";
130+ break;
131+ case 5: /* NOTICE */
132+ case 6: /* INFORMATION */
133+ result = "I";
134+ break;
135+ case 7: /* DEBUG */
136+ result = "D";
137+ break;
136138 }
137139 return result;
138140 }
@@ -165,7 +167,7 @@
165167 "local6",
166168 "local7",
167169 };
168- if(facility >= 0 && facility < names.Length){
170+ if (facility >= 0 && facility < names.Length) {
169171 return names[facility];
170172 }
171173 return null;
--- trunk/EWatch/EWatch/Watchers/WatchThread.cs (revision 110)
+++ trunk/EWatch/EWatch/Watchers/WatchThread.cs (revision 111)
@@ -77,7 +77,7 @@
7777 #if _WINDOWS
7878 Dictionary<string, List<ActionTable>> eventlogs = config.EventLog;
7979 foreach (string name in eventlogs.Keys) {
80- BaseWatcher watcher = new EventLogWatcher(name, eventlogs[name]);
80+ BaseWatcher watcher = new EventLogWatcher(config.General, name, eventlogs[name]);
8181 watchers.Add(watcher);
8282 }
8383 #endif
@@ -84,12 +84,12 @@
8484 Dictionary<string,List<ActionTable>> files = config.File;
8585 foreach(string path in files.Keys){
8686 var fileAndEncoding = FileAndEncoding.Parse(path);
87- BaseWatcher watcher = new FileWatcher(fileAndEncoding.File, fileAndEncoding.Encoding, files[path]);
87+ BaseWatcher watcher = new FileWatcher(config.General, fileAndEncoding.File, fileAndEncoding.Encoding, files[path]);
8888 watchers.Add(watcher);
8989 }
9090 Dictionary<string,List<ActionTable>> syslogs = config.Syslog;
9191 foreach(string port in syslogs.Keys){
92- BaseWatcher watcher = new SyslogServer(port, syslogs[port]);
92+ BaseWatcher watcher = new SyslogServer(config.General, port, syslogs[port]);
9393 watchers.Add(watcher);
9494 }
9595 }
--- trunk/EWatch/UnitTest/EWatch/Utils/EMailSenderTest.cs (revision 110)
+++ trunk/EWatch/UnitTest/EWatch/Utils/EMailSenderTest.cs (revision 111)
@@ -30,7 +30,7 @@
3030 "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"+
3131 "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"+
3232 "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
33- new MailAddress("test@test.com"), new MailAddress[]{ new MailAddress("test@test.com") }, null, null);
33+ new MailAddress("test@test.com"), new MailAddress[]{ new MailAddress("test@test.com") }, null, null, false);
3434
3535 }
3636 }
Show on old repository browser