기본 콘텐츠로 건너뛰기

[VSIX] Visual Studio 확장에 대해서... #5 Events and Commands

Events and Commands

이전 게시글에서 Wizard를 활용하는 방법을 정리해 보았다. 이번에는 추가된 INI 파일을 변경하고 저장하는 시점을 알아내서 관련된 처리를 수행할 수 있도록 처리하는 방법을 정리해 보도록 한다. 이 과정에서 필요한 것들이 Visual Stuidio에서 발생하는 이벤트들을 처리하는 것이며, 관련된 처리를 하기 위해서 Commands 를 호출하는 방법에 대해서 검토하게 된다.

Visual Studio Events

가장 먼저 처리해야 하는 부분이 DTE 와 Events 에 관련된 부분을 패키지에서 설정하는 부분이다. 아래의 그림과 같이 패키지 클래스에 관련된 정보를 설정할 수 있도록 코드를 구성한다.



   1:  private DTE dte;
   2:  private Events dteEvents;
   3:  private DocumentEvents documentEvents;
   4:   
   5:  private void setupEvents() {
   6:      this.dte = (DTE)this.GetService(typeof(SDTE));
   7:      this.dteEvents = this.dte.Events;
   8:      this.documentEvents = this.dteEvents.DocumentEvents;
   9:      this.documentEvents.DocumentSaved += onDocumentSaved;
  10:  }

위의 코드에서 확인할 수 있는 것처럼 많은 이벤트들이 제공되지만, 그 중에서도 INI 파일이 저장되는 경우에 처리를 수행할 것이기 때문에 “DocumentSaved” 이벤트를 사용하도록 한다. 이 이벤트에 전달되는 파라미터는 “Document” 로 내용이 수정된 문서 개체이다. 이 문서가 *.tini 파일인 경우에 한해서 자식으로 연결되어 있는 *.cs 파일을 찾아서 필요한 처리를 지정한다. 아래의 코드는 그런 작업을 수행하는 것이다.

   1:  private void onDocumentSaved(Document document) {
   2:      string path = document.FullName;
   3:      string ext = Path.GetExtension(path);
   4:      if (null == ext || ".tini" != ext.ToLowerInvariant()) return;
   5:   
   6:      ProjectItem source = null;
   7:      foreach (ProjectItem file in document.ProjectItem.ProjectItems) {
   8:          source = file;
   9:          break;
  10:      }
  11:      if (null == source) return;
  12:      try {
  13:          source.Open();
  14:      } finally {
  15:          if (null != source.Document) source.Document.Close();
  16:      }
  17:  }

위의 코드를 확인하면 13번째 라인에서 찾은 자식 *.cs 파일을 열었다가 15번째 라인에서 다시 닫은 것을 볼 수 있다. 지금은 단지 연계된 파일을 검색하는 수준이기 때문이다.


Get content of Document and save

우리가 사용할 수 있는 Document라는 개체는 명확하게 문서를 의미하는 개체는 아니라서 실제 문서 개체를 얻기 위해서는 Object 메서드를 통해서 얻어야 한다. 이를 통해서 “TextDocument” 개체를 얻을 수 있는데, 이 개체는 편집 위치들을 가지고 있기 때문에 처리할 영역에 대한 시작과 끝 위치를 지정해 주어야 한다. 현재 예제에서는 전체 영역을 다 사용하는 것으로 한다. 그리고 내용을 변경한 다음에 변경된 내용을 저장한다.

아래의 코드는 이런 작업을 수행하는 것이다.

   1:  private static string getDocumentText(Document document) {
   2:      TextDocument textDocument = (TextDocument)document.Object("TextDocument");
   3:      EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
   4:      string content = editPoint.GetText(textDocument.EndPoint);
   5:      return content;
   6:  }
   7:   
   8:  private static void saveDocumentText(Document document, string content) {
   9:      TextDocument textDocument = (TextDocument)document.Object("TextDocument");
  10:      EditPoint startPoint = textDocument.StartPoint.CreateEditPoint();
  11:      EditPoint endPoint = textDocument.EndPoint.CreateEditPoint();
  12:      startPoint.ReplaceText(endPoint, content, 0);
  13:      document.Save();
  14:  }

INI file parser

처음 예제에 템플릿을 추가할 때는 *.tini 파일의 자식으로 INI 파일 운영을 위한 클래스를 같이 생성했었다. 그러나 이제는 INI 파일이 변경된 경우에도 처리할 수 있도록 클래스를 재 생성해 주어야 하는 상황이 발생했으므로 이를 처리하기 위해서는 우선 INI 파일의 정보를 읽어 들이는 Parser 가 필요하다. 이름은 “INIParser.cs” 로 하고 FDTWorksTool.Library 프로젝트에 “Parsers” 폴더를 추가한 후에 클래스를 추가하고 아래의 코드와 같이 구성하도록 한다.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Globalization;
   4:  using System.Linq;
   5:  using System.Text;
   6:  using System.Threading.Tasks;
   7:   
   8:  namespace FDTWorksTool.Library.Parsers {
   9:      public class INIParser {
  10:          #region Fields
  11:   
  12:          private readonly string iniContent;
  13:          private readonly Dictionary<string, Dictionary<string, string>> content;
  14:   
  15:          #endregion
  16:   
  17:          #region Constructors
  18:   
  19:          public INIParser(string content) {
  20:              this.iniContent = content;
  21:              this.content = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
  22:              this.Load();
  23:          }
  24:   
  25:          #endregion
  26:   
  27:          #region Properties
  28:   
  29:          public string IniPath { get; private set; }
  30:          public CultureInfo Culture { get; private set; }
  31:          public IEnumerable<string> Categories {
  32:              get {
  33:                  foreach (var item in this.content)
  34:                      yield return item.Key;
  35:              }
  36:          }
  37:   
  38:          #endregion
  39:   
  40:          #region Methdos
  41:   
  42:          public void Load() {
  43:              string section = null;
  44:              this.content.Clear();
  45:              foreach (string line in this.iniContent.Split(new[] { '\r', '\f', '\n' })) {
  46:                  string prepared = line.Trim();
  47:                  if (string.IsNullOrWhiteSpace(prepared)) continue;
  48:                  if (line.StartsWith("[") || line.EndsWith("]")) {
  49:                      section = prepared.Substring(1, prepared.Length - 2);
  50:                      this.content.Add(section, new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase));
  51:                  } else if (!line.StartsWith("#") && !string.IsNullOrWhiteSpace(line) && section != null) {
  52:                      int expl = line.IndexOf('=');
  53:                      if (expl > 0)
  54:                          this.content[section][line.Substring(0, expl)] = line.Substring(expl + 1);
  55:                      else
  56:                          this.content[section][line] = "";
  57:                  }
  58:              }
  59:          }
  60:   
  61:          public IEnumerable<string> GetCategoryItems(string section) {
  62:              if (!this.content.ContainsKey(section)) yield break;
  63:              foreach (var kvp in this.content[section])
  64:                  yield return kvp.Key;
  65:          }
  66:   
  67:          public string GetValue(string id, string section) {
  68:              if (!this.content.ContainsKey(section)) return null;
  69:              if (!this.content[section].ContainsKey(id)) return null;
  70:              return this.content[section][id];
  71:          }
  72:   
  73:          #endregion
  74:      }
  75:  }

위의 코드는 INI 파일을 읽어서 구성된 데이터를 Dictionary> 포맷으로 관리하기 위한 것이다. 즉, 섹션 별로 키/값 들을 관리하는 것이다.

이제 *.tini 파일에 연계되어 있는 *.cs 파일을 읽어서 INI 파일의 내용에 따라서 아래와 같은 구성이 될 수 있도록 Parser를 구성하여야 한다.
  • 섹션과 연계되는 클래스들 선언 – “/*classes{{*/” ~ /*}}*/ 내부 내용 치환
  • 섹션 내의 값과 연동되는 변수들 선언 – “/*variables{{*/” ~ /*}}*/ 내부 내용 치환
  • 섹션 정보 초기화 – “/*initialize{{*/” ~ /*}}*/ 내부 내용 치환
  • 섹션 값 로드 – “/*load{{*/” ~ /*}}*/ 내부 내용 치환
  • 섹션 값 저장 – “/*save{{*/” ~ /*}}*/ 내부 내용 치환
물론 기존에 추가했었던 INIParserTemplate에 있는 iniTemplate.cs 파일도 아래의 코드와 같이 치환 영역을 미리 설정해 두어야 한다.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Globalization;
   4:  using System.IO;
   5:   
   6:  $if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
   7:  $endif$
   8:   
   9:  namespace $rootnamespace$
  10:  {
  11:      public class $safeitemrootname$
  12:      {
  13:          #region Internal Classes
  14:          
  15:          /*classes{{*/
  16:          /*}}*/
  17:   
  18:          #endregion
  19:   
  20:          #region Internal Variabels
  21:          
  22:          /*variables{{*/
  23:          /*}}*/
  24:   
  25:          #endregion
  26:   
  27:          #region Fields
  28:          
  29:          private readonly Dictionary<string, Dictionary<string, string>> content;
  30:   
  31:          #endregion
  32:   
  33:          #region Constructors
  34:          
  35:          public $safeitemrootname$(string path, CultureInfo culture) {
  36:              // Initialize the internal data structures
  37:              /*initialize{{*/
  38:              /*}}*/
  39:              this.IniPath = path;
  40:              this.Culture = culture;
  41:              this.content = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
  42:              if (!File.Exists(path)) {
  43:                  this.Save();
  44:              }
  45:              this.Load();
  46:          }
  47:   
  48:          #endregion
  49:   
  50:          #region Properties
  51:   
  52:          public string IniPath { get; private set; }
  53:          public CultureInfo Culture { get; private set; }
  54:           
  55:          #endregion
  56:   
  57:          #region Methods
  58:          
  59:          public void Load() {
  60:              string section = null;
  61:              this.content.Clear();
  62:              foreach(var line in File.ReadAllLines(this.IniPath)) {
  63:                  var prepared = line.Trim();
  64:                  if (line.StartsWith("[") && line.EndsWith("]")) {
  65:                      section = prepared.Substring(1, prepared.Length - 2);
  66:                      this.content.Add(section, new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase));
  67:                  } else if (!line.StartsWith("#") && !string.IsNullOrWhiteSpace(line) && section != null) {
  68:                      var expl = line.IndexOf('=');
  69:                      if (expl > 0)
  70:                          this.content[section][line.Substring(0, expl)] = line.Substring(expl + 1);
  71:                  }
  72:              }
  73:   
  74:              // After this the categoris classes will be loaded
  75:              /*load{{*/
  76:              /*}}*/
  77:          }
  78:   
  79:          public void Save() {
  80:              // After this the categories classes will be saved
  81:              /*save{{*/
  82:              /*}}*/
  83:              var text = string.Empty;
  84:              text += this.WriteLine("[INISetup]");
  85:              text += this.WriteLine("Culture=" + this.Culture.Name);
  86:   
  87:              foreach(var category in this.content) {
  88:                  var cat = category;
  89:                  if (cat.Key != "INISetup") {
  90:                      text += this.WriteLine("[" + cat.Key + "]");
  91:                      foreach(var val in cat.Value) {
  92:                          text += this.WriteLine(val.Key + "=" + val.Value);
  93:                      }
  94:                  }
  95:              }
  96:              File.WriteAllText(this.IniPath, text);
  97:          }
  98:   
  99:          public string GetValue(string id, string section) {
 100:              if (!this.content.ContainsKey(section)) return null;
 101:              if (!this.content[section].ContainsKey(id)) return null;
 102:              return this.content[section][id];
 103:          }
 104:   
 105:          public void SetValue(string id, string section, string value) {
 106:              if (!this.content.ContainsKey(section)) return null;
 107:              if (!this.content[section].ContainsKey(id)) return null;
 108:              this.content[section][id] = value;
 109:          }
 110:   
 111:          public string WriteLine(string line) {
 112:              return line + "\r\n";
 113:          }
 114:   
 115:          #endregion
 116:      }
 117:  }

이런 처리를 수행하기 위해서 “INIClassParser.cs” 라는 이름으로 클래스를 추가하고 아래의 코드로 설정해야 한다. 현재는 정식으로 처리하는 것이 아니고 문장열로 클래스를 구성하는 방식을 사용하고 있기 때문에 약간의 변수 치환 방식을 사용하여 코드를 구성하도록 한다. 아래의 코드는 처리를 수행하도록구성된 클래스다.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using System.Threading.Tasks;
   6:   
   7:  namespace FDTWorksTool.Library.Parsers {
   8:      public class INIClassParser {
   9:          #region Fields
  10:   
  11:          private string iniClassContent;
  12:          private readonly INIParser parser;
  13:   
  14:          #endregion
  15:   
  16:          #region Constructors
  17:   
  18:          public INIClassParser(string iniClassContent, INIParser parser) {
  19:              this.iniClassContent = iniClassContent;
  20:              this.parser = parser;
  21:          }
  22:   
  23:          #endregion
  24:   
  25:          #region Methods
  26:   
  27:          public string Parse() {
  28:              string iniClasses = string.Empty;
  29:              string iniVariables = string.Empty;
  30:              string iniInitialize = string.Empty;
  31:              string iniLoad = string.Empty;
  32:              string iniSave = string.Empty;
  33:   
  34:              write("/*classes{{*/", ref iniClasses);
  35:              write("/*variables{{*/", ref iniVariables);
  36:              write("/*initialize{{*/", ref iniInitialize);
  37:              write("/*load{{*/", ref iniLoad);
  38:              write("/*save{{*/", ref iniSave);
  39:   
  40:              foreach (string section in this.parser.Categories) {
  41:                  if (section == "INISetup") continue;
  42:                  var varName = firstUppercase(section);
  43:                  var className = varName + "Class";
  44:   
  45:                  write(string.Format("\t\t{1} = new {0}();", className, varName), ref iniInitialize);
  46:                  write(string.Format("\tpublic {0} {1} {{ get; private set; }}", className, varName), ref iniVariables);
  47:                  write("", ref iniClasses);
  48:                  write(string.Format("\tpublic class {0} {{", className), ref iniClasses);
  49:   
  50:                  foreach (string single in this.parser.GetCategoryItems(section)) {
  51:                      string singleName = firstUppercase(single);
  52:                      string singleValue = this.parser.GetValue(singleName, section);
  53:                      if (null == singleValue) singleValue = string.Empty;
  54:                      string singleValueCleaned = singleValue.Replace("\"", "\\\"");
  55:   
  56:                      write(string.Format("\t\t{0}.{1}=\"{2}\";", varName, singleName, singleValueCleaned), ref iniInitialize);
  57:                      write(string.Format("\t\t{0}.{1} = this.GetValue(\"{1}\", \"{0}\");", varName, singleName), ref iniLoad);
  58:                      write(string.Format("\t\tthis.SetValue(\"{1}\", \"{0}\", {0}, {1});", varName, singleName), ref iniSave);
  59:                      write(string.Format("\t\tpublic string {0} {{ get; set; }}", singleName), ref iniClasses);
  60:                  }
  61:   
  62:                  write("\t}", ref iniClasses);
  63:              }
  64:   
  65:              write("\t/*}}*/", ref iniClasses);
  66:              write("\t/*}}*/", ref iniVariables);
  67:              write("\t\t/*}}*/", ref iniLoad);
  68:              write("\t\t/*}}*/", ref iniSave);
  69:   
  70:              this.replaceBlock("/*classes{{*/", "/*}}*/", iniClasses);
  71:              this.replaceBlock("/*variables{{*/", "/*}}*/", iniVariables);
  72:              this.replaceBlock("/*intialize{{*/", "/*}}*/", iniInitialize);
  73:              this.replaceBlock("/*load{{*/", "/*}}*/", iniLoad);
  74:              this.replaceBlock("/*save{{*/", "/*}}*/", iniSave);
  75:   
  76:              return this.iniClassContent.Replace("\r\n\r\n", "\r\n");
  77:          }
  78:   
  79:          private void replaceBlock(string from, string to, string with) {
  80:              int start = this.iniClassContent.IndexOf(from, StringComparison.InvariantCultureIgnoreCase);
  81:              if (start < 0) throw new ArgumentException("Missing start tag " + from, "from");
  82:              int end = this.iniClassContent.IndexOf(to, StringComparison.InvariantCultureIgnoreCase);
  83:              if (end < 0) throw new ArgumentException("Missing end tag " + to, "to");
  84:   
  85:              string newContent = this.iniClassContent.Substring(0, start);
  86:              newContent += with;
  87:              newContent += this.iniClassContent.Substring(end);
  88:              this.iniClassContent = newContent;
  89:          }
  90:   
  91:          #endregion
  92:   
  93:          #region Static Methods
  94:   
  95:          private static void write(string write, ref string content, bool crLf = true) {
  96:              content += write;
  97:              if (crLf) content += "\r\n";
  98:          }
  99:   
 100:          private static string firstUppercase(string target) {
 101:              return target.Substring(0, 1).ToUpper() + target.Substring(1);
 102:          }
 103:   
 104:          #endregion
 105:      }
 106:  }

파서 구성이 되었으므로 위에서 잠시 언급했던 INI 파일이 저장되는 시점의 이벤트에서 INI 파일의 내용을 읽어서 연계된 *.cs 파일의 내용을 Parser 를 통해서 재 구성하는 부분을 아래의 그림과 같이 추가해 주어야 한다.

이미지 1

Connect to Command

이제 내부적으로 INI 파일이 저장되는 시점에 처리는 완성이 되었으므로 저장 시점이 아니라도 클래스를 재 생성할 수 있도록 Visual Studio 에서 메뉴를 사용해서 처리가 될 수 있도록 Command 와 연결할 필요가 있다. 이전 게시글에서 항목의 Context Menu 에 FDTWorks > Generate Ini 메뉴를 추가했던 것을 기억할 수 있을 것이다. 이번에는 그 메뉴의 Command 에 클래스 재 생성을 연결하는 코드를 아래와 같이 작성하면 된다.

이미지 2

Command Visibility

추가적으로 특정한 파일을 선택한 경우만 Menu 가 보이도록 하면 더 좋은 사용자 편의가 제공되는 것이기 때문에 다음과 같이 Menu 처리를 변경하도록 한다. 기존 패키지 클래스의 initialize 부분에서 구성했던 MenuCommand 에 “Before Query State” 이벤트를 추가로 연결하여 선택된 파일이 뭔지에 따라서 해당 메뉴의 Visibility를 변경하도록 아래와 같이 구성한다.

이미지 3

메뉴를 동적으로 보여질 수 있도록 처리를 했으므로 이제는 Visual Studio 가 동적으로 Menu 에 사용하는 Button을 동적으로 보여줄 수 있도록 Command 들을 정의했던 *.vsct 파일에도 설정을 해 주어야 한다.

이미지 4

이제 모든 작업이 완성되었다. 실행을 해서 INI 파일을 변경하고 저장을 하는 경우와 INI 파일을 선택하고 메뉴를 사용해서 해당 클래스가 제대로 생성이 되는지를 확인해 보면 된다.

아마 제대로 수행되는 것처럼 보이겠지만, 몇 가지 오류 상황들이 숨어있을 수 있기 때문에 지금까지 작업한 것을 이해하고, 관련된 흐름이 어떻게 운영되지는지를 이해할 겸해서 오류를 잡아서 완전하게 수행되는 버전을 완성시키는 것도 큰 도움이 될 것이다. ^^ 

댓글

이 블로그의 인기 게시물

OData 에 대해서 알아보자.

얼마 전에 어떤 회사에 인터뷰를 하러 간 적이 있었다. 당시 그 회사는 자체 솔루션을 개발할 기술인력을 찾고 있었고 내부적으로 OData를 사용한다고 했다. 좀 창피한 이야기일 수도 있지만 나름 기술적인 부분에서는 많은 정보를 가지고 있다고 했던 것이 무색하게 OData란 단어를 그 회사 사장님에게서 처음 들었다. 작고, 단순한 사이트들만을 계속해서 작업을 하다 보니 어느덧 큰 줄기들을 잃어버린 것을 느끼기 시작했다. 명색이 개발이 좋고, 기술적인 기반을 만들려고 하는 인간이 단어조차도 모른다는 것은 있을 수 없는 것이라서 다시 새로운 단어들과 개념들을 알아보는 시간을 가지려고 한다. OData (Open Data Protocol) 란? 간단히 정리하면 웹 상에서 손쉽게 데이터를 조회하거나 수정할 수 있도록 주고 받는 웹(프로토콜)을 말한다. 서비스 제공자 입장에서는 웹으로 데이터를 제공하는 방식으로 각 포탈 사이트들이 제공하는 OPEN API 포맷을 독자적인 형식이 아니라 오픈된 공통규약으로 제공 가능하며, 개발자는 이 정보를 다양한 언어의 클라이언트 라이브러리로 어플리케이션에서 소비할 수 있도록 사용하면 된다. 공식 사이트는 www.odata.org 이며 많은 언어들을 지원하고 있다. 좀더 상세하게 정의를 해 보면 OData는 Atom Publishing Protocol  (RFC4287) 의 확장 형식이고 REST (REpresentational State Transfer) Protocol 이다. 따라서 웹 브라우저에서 OData 서비스로 노출된 데이터를 볼 수 있다. 그리고 AtomPub 의 확장이라고 했듯이 데이터의 조회만으로 한정되는 것이 아니라 CRUD 작업이 모두 가능하다. Example 웹 브라우저에서 http://services.odata.org/website/odata.svc 를 열어 보도록 하자. This XML file does not appear to have any style in...

C# 에서 Timer 사용할 때 주의할 점.

예전에 알고 지내시던 분의 질문을 받았다. Windows Forms 개발을 하는데, 주기적 (대략 1분)으로 데이터 요청을 하는 프로그램을 작성하기 위해서 Timer 를 사용하는데, 어떤 기능을 처리해야 하기 때문에 Sleep 을 같이 사용했다고 한다. 여기서 발생하는 문제는 Sleep 5초를 주었더니, Timer 까지 5초 동안 멈춘다는 것이다. Timer 라는 것은 기본적으로 시간의 흐름을 측정하는 기능이기 때문에 Sleep 을 했다고 해서 Timer 가 멈추는 일은 생겨서는 안된다. 그러나 실제 샘플을 만들어 보면 ... Timer 가 Sleep 만큼 동작이 멈추는 것을 확인할 수 있다. Windows Forms 는 UI Thread 를 사용하는 것으로 최적화 되어 있으며 여기서 Timer 를 쓰면 UI Thread 에 최적화된 System.Windows.Forms.Timer 가 사용된다. 여기서 문제의 발생이 시작되는 것이다. Sleep 을 사용하게 되면 UI Thread 가 Sleep 이 걸리기 때문에 여기에 속한 Timer 까지도 멈추는 것이다. 이런 문제를 해결하기 위해서는 System.Threading.Timer 를 사용해야 한다. 이 Timer 는 별도의 Thread 에서 동작하기 때문에 Sleep 의 영향을 받지 않는다. 언뜻 보면 쉬운 해결 방법인 것 같지만 Thread 가 분리되었기 때문에 Timer 가 돌아가는 Thread 에서 UI Thread 의 메서드나 컨트롤에 접근하기 위해서는 별도의 명령을 사용해야 하는 문제가 존재한다. 자~ 그럼 여기서 Timer 에 대해서 다시 한번 정리해 보도록 하자. .NET 에서 제공하는 Timer 들 .NET 에서는 기본적으로 3가지 Timer를 제공하고 있다. (MSDN) System.Windows.Forms.Timer - 사용자가 지정한 간격마다 이벤트를 발생시키며 Windows Forms 응용 프로그램에서 사용할 수 있도록 최적화 되어 있다. System...

[Logging] NLog 사용법 정리...

SCSF 에는 기본적으로 Enterprise Library가 사용된다. 예전에도 그랬지만 기능은 훌륭하고 많은 부분에서 최적화(?)된 것일지도 모르지만, 역시나 사용하기에는 뭔가 모르게 무겁고, 사용하지 않는 기능이 더 많다라는 느낌을 지울수가 없다. 이번 프로젝트도 SCSF를 기반으로 하고 있지만, Enterprise Library를 걷어내고 각 부분에 전문화된 오픈 소스를 사용하기로 하였다. 예전에는 Log4Net을 사용했지만, 대량 사용자 환경에서는 메모리 누수와 기타 문제점이 존재한다는 MS 컨설턴트(?)의 전해진 말을 들은 후로는 사용하지 않는다. 대안으로 사용하는 것이 NLog 이다. 조금 후에는 3.0 버전도 나온다고 홈 페이지에 기재되어 있지만, 그 때가 되면 프로젝트는 끝나기 때문에 현재 2.1.0 버전을 사용하기로 했다. [원본 출처] http://cloverink.net/most-useful-nlog-configurations-closed/ 위의 참조 자료에는 다양한 정보들이 존재하므로 꼭 링크를 통해서 관련된 정보를 확인하고 이해하는 것이 좋을 듯 하다. 여기서는 당장 필요한 부분만을 정리하도록 한다. [ Logger 찾기 ] 기본적으로 Logger가 존재하는 클래스를 기반으로 Logger 정보를 구성한다. Logger logger = LogManager.GetCurrentClassLogger(); 주로 Namespace 기반으로 Logger를 설정하는 경우에 유연하게 사용할 수 있다. 또 다른 방법으로는 지정한 문자열로 특정 Logger를 직접 선택하는 방법도 제공된다. 이를 혼용해서 Namespace와 직접 지정 방식을 같이 사용할 수도 있다. 물론 Logger 환경 설정에서 Wildcard (*)를 지정할 수도 있다. Logger logger = LogManager.GetLogger("Database.Connect"); Logger logger = LogManager.Get...