2008/05 에 해당하는 글1 개
2008/05/28   [WMI] 프로세스의 CPU_메모리 사용량_네트워크 트래픽을 Log로 저장 (2)


[WMI] 프로세스의 CPU_메모리 사용량_네트워크 트래픽을 Log로 저장
프로그래밍/WMI 스크립트 | 2008/05/28 03:30

서버 프로그래머는 CPU와 메모리 사용량에 많은 관심을 가지게 된다.
서버 프로그램, 즉 Process가 CPU 100%로 사용중이거나 메모리가 2GB(User Memory)에 근접하게 되면 곤란한 경우가 많다.
그래서 종종 OS에서 제공하는 성능 모니터를 이용해서 Log를 남기기도 하는데, Process를 추가하기도 번거롭고 결과물을 EXCEL로 편집하기도 까다롭다.
이번 기회에 WMI 스크립트를 이용해서 Process 이름만 바꿔주고 클릭하면 10초마다 Log를 남기도록 만들었다.(스크립트 기반이므로 누구나 손쉽게 수정하여 사용 가능하다.)
네트워크 트래픽은 네트워크 어댑터 중에서 가장 송/수신이 많은 어댑터의 트래픽을 기록한다.( 단일 프로세스의 트래픽을 기록하는 것이 아니다. )

주의사항 : WbemScripting.SWbemRefresher 객체를 지원하는 OS는 다음과 같다.
Windows XP SP2 이상
Windows Server 2003 이상

Option Explicit
 
Dim FSO, oFile
Dim objWMIService, objProcess, objPerfOS, objNetworkInterface, objRefresher
Dim colProcess, colPerfOS, colPerfNetworkInterface
Dim strComputer, strFileName, strCpuPercent, strProcess
Dim strProcessName, strProcessNameForPerf
Dim strDate, strTime
Dim DateEnd, Timelimit
 
'프로세스 이름(.exe는 제거한다.)
strProcessNameForPerf = "explorer"
strProcessName = strProcessNameForPerf & ".exe"
 
'Log 남길 시간 설정
' "y"  년
' "m"  월
' "d"  일
' "w"  주
' "h"  시
' "n"  분
' "s"  초
 
Timelimit = 1
DateEnd = DateAdd("n", Timelimit, Now)
 
'strFileName = Inputbox("c:\ProcessPerformanceLog.txt","Process Performance","ProcessPerformanceLog.txt")
strFileName = strProcessNameForPerf & "_" & "ProcessPerformanceLog.txt"
 
'시스템 Object 생성
Set FSO = CreateObject("Scripting.FileSystemObject")
Set oFile = FSO.CreateTextFile(strFileName, True)
 
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
 
'새로고침 Object 생성
Set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
 
Set colPerfOS = objRefresher.AddEnum(objWMIService, "Win32_PerfFormattedData_PerfProc_Process").objectSet
Set colPerfNetworkInterface = objRefresher.AddEnum(objWMIService, "Win32_PerfFormattedData_Tcpip_NetworkInterface").objectSet
Set colProcess = objRefresher.AddEnum(objWMIService, "Win32_Process").objectSet
objRefresher.Refresh
Wscript.Sleep 1000
 
'Header 정보 Log 파일에 출력
oFile.Write("Date" & vbTab & "Time" & vbTab & "Process Name" & vbTab & "CPU Usage" & vbTab & "Memory Usage" & vbTab & "Peak Memory Usage" & vbTab & "PageFile Usage" & vbTab & "Peak PageFile Usage" & vbTab & "Network KBytesSendPerSec" & vbTab & "Network KBytesRecvPerSec")
 
While( Now < DateEnd )
   '시스템 정보 Refresh
   objRefresher.Refresh
 
   '네트워크 트래픽 보기 - 모든 네트워크 어댑터에서 중에서 송/수신량이 가장 많은 어댑터의 트래픽을 기록한다.
   Dim nBytesSentPerSec : nBytesSentPerSec = 0
   Dim nBytesReceivedPerSec : nBytesReceivedPerSec = 0
 
   For Each objNetworkInterface in colPerfNetworkInterface
      If ( nBytesSentPerSec < objNetworkInterface.BytesSentPerSec ) Then
         nBytesSentPerSec = objNetworkInterface.BytesSentPerSec
      End If
 
      If ( nBytesReceivedPerSec < objNetworkInterface.BytesReceivedPerSec ) Then
         nBytesReceivedPerSec = objNetworkInterface.BytesReceivedPerSec
      End If
   Next
 
   'CPU 사용량 보기
   For Each objPerfOS in colPerfOS
      If ( strProcessNameForPerf = objPerfOS.Name ) Then
         strCpuPercent = objPerfOS.PercentProcessorTime
      End If
   Next
 
   '프로세스 메모리 보기
   For Each objProcess in colProcess
      If ( strProcessName = objProcess.Name ) Then
         GetDate strDate
         GetTime strTime
         strProcess = vbNewLine & strDate & vbTab & strTime & vbTab & objProcess.Name & vbTab & strCpuPercent & vbTab & objProcess.WorkingSetSize/1024 & "KB" & vbTab & objProcess.PeakWorkingSetSize/1024 & "KB" & vbTab & objProcess.PageFileUsage/1024 & "KB" & vbTab & objProcess.PeakPageFileUsage/1024 & "KB" & vbTab & int(nBytesSentPerSec/1024) & "KB" & vbTab & int(nBytesReceivedPerSec/1024) & "KB"
      End If
   Next
 
   'Log 파일에 저장
   oFile.Write(strProcess)
 
   '10초마다 한번씩 로그를 남긴다.
   Wscript.Sleep 10000
WEnd
 
oFile.Write( vbNewLine & "End of Log" )
oFile.Close
WScript.Quit
 
 
'Sub 함수들
Sub GetTime( strTime )
Dim strHour, strMinute, strSecond
 
'--  Hour 2자리로 변경
strHour = Hour(Now)
If Len(strHour) < 2 Then
  strHour = "0" & strHour
End If
 
'-- Minute 2자리로 변경
strMinute = Minute(Now)
If Len(strMinute) < 2 Then
  strMinute = "0" & strMinute
End If
 
'-- Second
strSecond = Second(Now)
If Len(strSecond) < 2 Then
  strSecond = "0" & strSecond
End If
 
'-- 전체 시간
strTime = strHour & ":" & strMinute & ":" & strSecond
 
End Sub
 
 
Sub GetDate( strDate )
Dim strDay, strMonth, strYear
 
'--  Day 2자리로 변경
strDay = Day(Now)
If Len(strDay) < 2 Then
  strDay = "0" & strDay
End If
 
'-- Month 2자리로 변경
strMonth = Month(Now)
If Len(strMonth) < 2 Then
  strMonth = "0" & strMonth
End If
 
'-- Year
strYear = Year(Now)
 
'-- 전체 날짜 구하기
strDate = strYear & "-" & strMonth & "-" & strDay
 
End Sub
 
kkamagui 2008/05/13 07:59
와우~ 멋지군요. ;)
좋은 코드 잘 보고 갑니다. ^^
퍼가고 트랙백 남기겠습니다. ^^)/~
TTF 2008/05/13 10:57
네 유용하게 쓰셨으면 좋겠어요.
트랙백 스팸 때문에 트랙백은 막아 놓았습니다.
Name
Password
Homepage
  Secret
Description
 

BLOG main image
전체 (357)
Project (7)
TTF 강좌 (21)
Tip&Tech (57)
프로그래밍 (146)
DATABASE (9)
자료실 (103)
디아블로2 (2)
TTF 개인.. (11)
영어 관련 (0)
<<   2008/05   >>
S M T W T F S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
2008/10
2008/09
2008/08
2008/07
2008/06
관리자만 볼..
    11/06 -
관리자만 볼..
    10/06 -
관리자만 볼..
    10/02 -
http://supp..
    09/30 - TTF
감사합니다...
    09/26 - 이상곤
VC6에서 UNI..
    2006 - HaruSchool
ActiveX 상..
ADODB, OLED..
bootflashdo..
CD 없이 게..
CNX 17기 썽..
code2dive ..
CodeProject..
codeway - ..
ColorSchemes
cpueblo's b..
Crystal Flo..
C프로그래밍..
DataBaser.net
DB 디자인 ..
DirectX 9.0..
Dual - 네이..
Dual - 홈페..
DVD인포 국..
Encoding, D..
FastDelegate
guru 3d(최..
http 파일 ..
IBM UML링크
INF, WMI, V..
Inxzone - ..
MFC 관련 네..
MFC 기초 강..
MFC 유용한 ..
MFC 컨트롤 ..
MS 다운로드..
MSDN shell ..
MSDN 공용 ..
Mysql DB 디..
Naughter의 ..
POSA2 DEVPI..
SQL Compact
SVN NOTIFY
TCP 레지스..
Time4Crime(..
UML Case To..
UML 관련 정..
vc++ 소스와..
vivaman - ..
Win32 Debug..
winapi - AP..
xlsvba 카페
XType님의 ..
yoda의 홈페..
가상 플로피..
구글번역(영..
구글번역(한..
김상욱 개발..
김태형님 블..
꿀뷰
네이버 지하..
대한민국 법..
디버거 툴 ..
디버그 랩
디스어셈블..
마소 TechNet
망사2 PC방 ..
메뉴얼 언패..
미디어 컨버트
버그 리포트..
비스무리(송..
비주얼 베이..
서울시 버스..
서울시교통..
스프링노트
시디 커버 ..
시디알인포 ..
신용우님 FP..
신화방송국
싸미월드
안준석님 블..
알고리즘 심..
언패킹 강좌..
여리의 작업실
영어 듣기 ..
온라인 게임..
윈도우 프로..
유경상의 닷..
인크레디빌드
자바스크립..
전자 부품 ..
전화번호로 ..
정명수님 블..
정보보안연..
지니네 - 네..
지니야 홈페..
찬희와 희야
최흥배님 카..
카페 24 - ..
커플이님의 ..
클래스 뷰 ..
통계 정보 ..
통합전자민..
프로젝트 관리
한국 TOC 컨..
한국전산원 ..
해외거주 한..
휘슬러 사용..
180
16
104077
태터툴즈 배너