성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Roll A Lisp In C - Reading ; https...
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제</h1> <p> 전에 쓴 글에,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - (.NET Core 2.2부터 가능한) 프로세스 내부에서 CLR ETW 이벤트 수신 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12474'>https://www.sysnet.pe.kr/2/0/12474</a> </pre> <br /> GCHeapStats_V1, GCHeapStats_V2 이벤트를,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > GCHeapStats_V2 Event ; <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcheapstats_v2-event'>https://learn.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcheapstats_v2-event</a> </pre> <br /> 받으려고 다음과 같이 소스코드를 작성했습니다.<br /> <br /> <pre style='height: 400px; margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Diagnostics.Tracing; using System.Linq; using System.Reflection; using System.Runtime.Versioning; class Program { static MyEventListener _listener; static Program() { _listener = new MyEventListener(<span style='color: blue; font-weight: bold'>DotnetRuntimeKeyword.GCKEYWORD</span>, new PrimitiveEnum[] { <span style='color: blue; font-weight: bold'>GCEvent.GCHeapStats_V2</span> }); } static void Main(string[] args) { Console.WriteLine(Environment.Version); Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription); // .NET Core 3.0.0-preview4.19113.15 Console.WriteLine(Assembly.GetEntryAssembly().GetCustomAttribute<TargetFrameworkAttribute>().FrameworkName); Console.WriteLine(Assembly.GetEntryAssembly().GetName().Version); Console.WriteLine("In-proc ETW Enabled on .NET Core 2.2 or later"); while (true) { string result = Console.ReadLine(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); } } } public enum DotnetRuntimeKeyword : long { GCKEYWORD = 0x01, } public enum GCEvent { GCStart_V1 = 1, GCEnd_V1 = 2, GCHeapStats_V1 = 4, GCHeapStats_V2 = 4, // https://learn.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcheapstats_v2-event GCCreateSegment_V1 = 5, GCFreeSegment_V1 = 6, GCRestartEEBegin_V1 = 7, GCRestartEEEnd_V1 = 3, GCSuspendEE_V1 = 9, GCSuspendEEEnd_V1 = 8, GCAllocationTick_V2 = 10, GCAllocationTick_V3 = 10, GCFinalizersBegin_V1 = 14, GCFinalizersEnd_V1 = 13, GCCreateConcurrentThread_V1 = 11, GCTerminateConcurrentThread_V1 = 12, } internal class MyEventListener : EventListener { // https://docs.microsoft.com/en-us/dotnet/framework/performance/clr-etw-keywords-and-levels EventSource _eventSource; long _filterKeyword; int[] _filterEventId; public MyEventListener(DotnetRuntimeKeyword filterKeyword, PrimitiveEnum[] filterEventId = null) { this._filterKeyword = (long)filterKeyword; this._filterEventId = filterEventId?.Select((elem) => (int)elem).ToArray(); this.EventSourceCreated += MyEventListener_EventSourceCreated; } private void MyEventListener_EventSourceCreated(object sender, EventSourceCreatedEventArgs e) { if (e.EventSource.Name == "Microsoft-Windows-DotNETRuntime") { _eventSource = e.EventSource; e.EventSource.EventCommandExecuted += EventSource_EventCommandExecuted; EnableEvents(e.EventSource, EventLevel.Informational, (EventKeywords)this._filterKeyword); } } private void EventSource_EventCommandExecuted(object sender, EventCommandEventArgs e) { if (e.Command == EventCommand.Enable) { // e.DisableEvent((int)ExceptionEvent.ExceptionThrown_V1); // e.DisableEvent((int)ExceptionEvent.ExceptionCatchStart); // e.DisableEvent((int)ExceptionEvent.ExceptionCatchStop); // e.DisableEvent((int)ExceptionEvent.ExceptionFinallyStart); // e.DisableEvent((int)ExceptionEvent.ExceptionFinallyStop); // e.DisableEvent((int)ExceptionEvent.ExceptionFilterStart); // e.DisableEvent((int)ExceptionEvent.ExceptionFilterStop); // e.DisableEvent((int)ExceptionEvent.ExceptionThrownStop); FilterEventId(_eventSource, e); } } private void FilterEventId(EventSource eventSource, EventCommandEventArgs e) { Type type = eventSource.GetType(); FieldInfo fi = type.GetField("m_eventData", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (fi != null) { object objMetadataArray = fi.GetValue(eventSource); // System.Diagnostics.Tracing.EventSource.EventMetadata [] System.Collections.IEnumerable enumerator = objMetadataArray as System.Collections.IEnumerable; foreach (object objItem in enumerator) { object descriptor = GetDescriptor(objItem); if (descriptor == null) { continue; } (long keyword, int eventId) = GetKeywordAndEventId(descriptor); if (((long)keyword & this._filterKeyword) == this._filterKeyword) { if (_filterEventId?.Contains(eventId) == false) { e.DisableEvent(eventId); } } } } } private (long, int) GetKeywordAndEventId(object descriptor) { object keyword = GetPropertyReflect(descriptor, "Keywords"); object eventValue = GetPropertyReflect(descriptor, "EventId"); if (keyword == null || eventValue == null) { return (0, 0); } return ((long)keyword, (int)eventValue); } private object GetDescriptor(object objItem) { return GetFieldReflect(objItem, "Descriptor"); } object GetPropertyReflect(object obj, string propertyName) { Type type = obj.GetType(); PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); if (pi != null) { return pi.GetValue(obj); } return null; } object GetFieldReflect(object obj, string fieldName) { Type type = obj.GetType(); FieldInfo fi = type.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance); if (fi != null) { return fi.GetValue(obj); } return null; } protected override void OnEventWritten(EventWrittenEventArgs eventData) { if (((long)eventData.Keywords & _filterKeyword) == _filterKeyword) { if (eventData.EventId == (int)GCEvent.GCHeapStats_V2) { Console.WriteLine($"{DateTime.Now}: {eventData.EventName}, {eventData.EventId}"); } } } } </pre> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1977&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> <br /> 위의 경우에는 테스트가 잘 되었는데, 이상하게도 저 MyEventListener 클래스를 .NET Core 2.2 + ASP.NET Core Web Application 환경에서 돌리면 그때부터 GCHeapStats_V2 이벤트가 수신되지 않습니다.<br /> <br /> 이거저거 살펴본 결과 ^^; (ASP.NET의 경우 설정 파일에 명시하고 있는) 서버 유형의 GC 모드가 동작하는 환경에서는 그런 문제가 발생했습니다. 그래서 위의 예제 코드에 "<a target='tab' href='https://www.sysnet.pe.kr/2/0/12983'>runtimeconfig.template.json</a>" 파일을 추가해 다음과 같은 설정을 추가하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > { "configProperties": { <span style='color: blue; font-weight: bold'>"System.GC.Server": true</span> } } </pre> <br /> 그 후부터 .NET Core 2.2 런타임에서는 동일한 현상이 재현됩니다. 재미있는 것은, .NET Core 3.0부터는 정상적으로 이벤트가 수신됩니다.<br /> <br /> 사실 .NET Core 2.2를 이제는 거의 사용하지 않을 것이므로 이제는 그냥 역사 속으로 묻힐 시행 착오에 불과한 이야기가 되는군요. ^^<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1007
(왼쪽의 숫자를 입력해야 합니다.)