github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/osext/winsvc/eventlog/log.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package eventlog implements access to Windows event log.
     6  //
     7  package eventlog
     8  
     9  import (
    10  	"chai2010.gopkg/osext/winsvc/winapi"
    11  	"errors"
    12  	"syscall"
    13  )
    14  
    15  // Log provides access to system log.
    16  type Log struct {
    17  	Handle syscall.Handle
    18  }
    19  
    20  // Open retrieves a handle to the specified event log.
    21  func Open(source string) (*Log, error) {
    22  	return OpenRemote("", source)
    23  }
    24  
    25  // OpenRemote does the same as Open, but on different computer host.
    26  func OpenRemote(host, source string) (*Log, error) {
    27  	if source == "" {
    28  		return nil, errors.New("Specify event log source")
    29  	}
    30  	var s *uint16
    31  	if host != "" {
    32  		s = syscall.StringToUTF16Ptr(host)
    33  	}
    34  	h, err := winapi.RegisterEventSource(s, syscall.StringToUTF16Ptr(source))
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  	return &Log{Handle: h}, nil
    39  }
    40  
    41  // Close closes event log l.
    42  func (l *Log) Close() error {
    43  	return winapi.DeregisterEventSource(l.Handle)
    44  }
    45  
    46  func (l *Log) report(etype uint16, eid uint32, msg string) error {
    47  	ss := []*uint16{syscall.StringToUTF16Ptr(msg)}
    48  	return winapi.ReportEvent(l.Handle, etype, 0, eid, 0, 1, 0, &ss[0], nil)
    49  }
    50  
    51  // Info writes an information event msg with event id eid to the end of event log l.
    52  // eid must be between 1 and 1000 if using EventCreate.exe as event message file.
    53  func (l *Log) Info(eid uint32, msg string) error {
    54  	return l.report(winapi.EVENTLOG_INFORMATION_TYPE, eid, msg)
    55  }
    56  
    57  // Warning writes an warning event msg with event id eid to the end of event log l.
    58  // eid must be between 1 and 1000 if using EventCreate.exe as event message file.
    59  func (l *Log) Warning(eid uint32, msg string) error {
    60  	return l.report(winapi.EVENTLOG_WARNING_TYPE, eid, msg)
    61  }
    62  
    63  // Error writes an error event msg with event id eid to the end of event log l.
    64  // eid must be between 1 and 1000 if using EventCreate.exe as event message file.
    65  func (l *Log) Error(eid uint32, msg string) error {
    66  	return l.report(winapi.EVENTLOG_ERROR_TYPE, eid, msg)
    67  }