You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/log/internal/log_writer.go

78 lines
1.4 KiB

9 years ago
package internal
import (
"log"
"os"
"github.com/v2ray/v2ray-core/common/platform"
)
9 years ago
type LogWriter interface {
9 years ago
Log(LogEntry)
}
9 years ago
type NoOpLogWriter struct {
}
9 years ago
func (this *NoOpLogWriter) Log(entry LogEntry) {
entry.Release()
}
9 years ago
type StdOutLogWriter struct {
logger *log.Logger
}
9 years ago
func NewStdOutLogWriter() LogWriter {
return &StdOutLogWriter{
logger: log.New(os.Stdout, "", log.Ldate|log.Ltime),
}
}
9 years ago
func (this *StdOutLogWriter) Log(log LogEntry) {
this.logger.Print(log.String() + platform.LineSeparator())
9 years ago
log.Release()
}
9 years ago
type FileLogWriter struct {
9 years ago
queue chan string
logger *log.Logger
file *os.File
}
9 years ago
func (this *FileLogWriter) Log(log LogEntry) {
select {
9 years ago
case this.queue <- log.String():
default:
// We don't expect this to happen, but don't want to block main thread as well.
}
9 years ago
log.Release()
}
9 years ago
func (this *FileLogWriter) run() {
9 years ago
for {
entry, open := <-this.queue
if !open {
break
}
9 years ago
this.logger.Print(entry + platform.LineSeparator())
}
}
9 years ago
func (this *FileLogWriter) Close() {
this.file.Close()
}
9 years ago
func NewFileLogWriter(path string) (*FileLogWriter, error) {
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return nil, err
}
9 years ago
logger := &FileLogWriter{
9 years ago
queue: make(chan string, 16),
logger: log.New(file, "", log.Ldate|log.Ltime),
file: file,
}
go logger.run()
return logger, nil
}