Compare commits

...

18 Commits

@ -5,24 +5,21 @@ import (
"os"
"path/filepath"
"time"
"b612.me/staros"
"b612.me/starmap"
)
var archMap starmap.StarMapKV
var archMap starMapKV
func init() {
archMap = starmap.NewStarMap()
archMap = newStarMap()
}
type Archive interface {
ShouldArchiveNow(string, os.FileInfo) bool
NextLogFilePath(string, os.FileInfo) string
ShouldArchiveNow(*StarLogger, string, os.FileInfo) bool
NextLogFilePath(*StarLogger, string, os.FileInfo) string
ArchiveLogFilePath(*StarLogger, string, os.FileInfo) string
Interval() int64
HookBeforArchive() func(string, os.FileInfo) error
HookAfterArchive() func(string, string, os.FileInfo) error
HookBeforArchive() func(*StarLogger, string, string, os.FileInfo) error //archivePath;currentPath
HookAfterArchive() func(*StarLogger, string, string, os.FileInfo) error //archivePath;currentPath
}
type logfileinfo struct {
@ -35,13 +32,13 @@ func SetLogFile(path string, logger *StarLogger, appendMode bool) error {
if appendMode {
fileMode = os.O_APPEND | os.O_CREATE | os.O_WRONLY
} else {
fileMode = os.O_CREATE | os.O_WRONLY
fileMode = os.O_CREATE | os.O_WRONLY | os.O_TRUNC
}
fullpath, err := filepath.Abs(path)
if err != nil {
return err
}
if !appendMode && staros.Exists(fullpath) {
if !appendMode && Exists(fullpath) {
os.Remove(fullpath)
}
fp, err := os.OpenFile(fullpath, fileMode, 0644)
@ -119,7 +116,7 @@ func StartArchive(logger *StarLogger, arch Archive) error {
select {
case <-stopChan:
return
case <-time.After(time.Second * time.Duration(arch.Interval())):
case <-time.After(time.Millisecond * time.Duration(1000*arch.Interval())):
}
fileinfo, err := GetLogFileInfo(logger)
if err != nil {
@ -131,21 +128,30 @@ func StartArchive(logger *StarLogger, arch Archive) error {
continue
}
fullpath := archMap.MustGet(logger.logcore.id).(logfileinfo).fullpath
if !arch.ShouldArchiveNow(fullpath, fileinfo) {
if !arch.ShouldArchiveNow(logger, fullpath, fileinfo) {
continue
}
newLogPath := arch.NextLogFilePath(fullpath, fileinfo)
newLogPath := arch.NextLogFilePath(logger, fullpath, fileinfo)
archiveLogPath := arch.ArchiveLogFilePath(logger, fullpath, fileinfo)
if arch.HookBeforArchive() != nil {
if err := arch.HookBeforArchive()(fullpath, fileinfo); err != nil {
if err := arch.HookBeforArchive()(logger, archiveLogPath, fullpath, fileinfo); err != nil {
logger.Errorf("error occur while executing hook before archive,detail is %v\n", err)
continue
}
}
err = CloseWithSwitching(logger)
if err != nil {
continue
}
err = os.Rename(fullpath, archiveLogPath)
if err != nil {
continue
}
if err := SetLogFile(newLogPath, logger, false); err != nil {
logger.Errorf("error occur while executing coverting new log file,detail is %v\n", err)
continue
} else {
logger.Debugln("Set Log Success")
logger.Debugln("Archive Log Success")
}
fileinfo, err = GetLogFileInfo(logger)
if err != nil {
@ -153,7 +159,7 @@ func StartArchive(logger *StarLogger, arch Archive) error {
continue
}
if arch.HookAfterArchive() != nil {
if err := arch.HookAfterArchive()(fullpath, newLogPath, fileinfo); err != nil {
if err := arch.HookAfterArchive()(logger, archiveLogPath, newLogPath, fileinfo); err != nil {
logger.Errorf("error occur while executing hook after archive,detail is %v\n", err)
continue
}
@ -178,23 +184,47 @@ func StopArchive(logger *StarLogger) {
}
type ArchiveByDate struct {
interval int64
checkInterval int64
newFileNameStyle string
hookBefor func(string, os.FileInfo) error
hookAfter func(string, string, os.FileInfo) error
interval int64
checkInterval int64
baseFileStyle string
archiveStyle string
lastSwitchTime time.Time
changeArchiveName bool
hookBefore func(*StarLogger, string, string, os.FileInfo) error
hookAfter func(*StarLogger, string, string, os.FileInfo) error
}
func (abd *ArchiveByDate) ShouldArchiveNow(fullpath string, info os.FileInfo) bool {
if time.Now().Unix()-staros.GetFileCreationTime(info).Unix() > abd.interval {
func (abd *ArchiveByDate) ShouldArchiveNow(l *StarLogger, fullpath string, info os.FileInfo) bool {
if abd.lastSwitchTime.IsZero() {
abd.lastSwitchTime = GetFileCreationTime(info)
}
sub := time.Now().Unix() - abd.lastSwitchTime.Unix()
if sub >= abd.interval || abd.interval-sub <= abd.checkInterval/2 {
return true
}
return false
}
func (abd *ArchiveByDate) NextLogFilePath(oldpath string, info os.FileInfo) string {
func (abd *ArchiveByDate) NextLogFilePath(l *StarLogger, oldpath string, info os.FileInfo) string {
var newName string
dir := filepath.Dir(oldpath)
newName := time.Now().Format(abd.newFileNameStyle)
if !abd.changeArchiveName {
newName = abd.baseFileStyle + time.Now().Format(abd.archiveStyle)
} else {
newName = abd.baseFileStyle
}
return filepath.Join(dir, newName)
}
func (abd *ArchiveByDate) ArchiveLogFilePath(l *StarLogger, oldpath string, info os.FileInfo) string {
var newName string
dir := filepath.Dir(oldpath)
if abd.changeArchiveName {
newName = filepath.Base(abd.baseFileStyle) + time.Now().Format(abd.archiveStyle)
} else {
newName = abd.baseFileStyle
}
return filepath.Join(dir, newName)
}
@ -202,52 +232,77 @@ func (abd *ArchiveByDate) Interval() int64 {
return abd.checkInterval
}
func (abd *ArchiveByDate) HookBeforArchive() func(string, os.FileInfo) error {
func (abd *ArchiveByDate) HookBeforArchive() func(*StarLogger, string, string, os.FileInfo) error {
return abd.hookBefor
return abd.hookBefore
}
func (abd *ArchiveByDate) HookAfterArchive() func(string, string, os.FileInfo) error {
return abd.hookAfter
func (abd *ArchiveByDate) HookAfterArchive() func(*StarLogger, string, string, os.FileInfo) error {
return func(logger *StarLogger, s string, s2 string, info os.FileInfo) error {
abd.lastSwitchTime = time.Now()
if abd.hookAfter != nil {
return abd.hookAfter(logger, s, s2, info)
}
return nil
}
}
func (abd *ArchiveByDate) SetHookBeforArchive(f func(string, os.FileInfo) error) {
abd.hookBefor = f
func (abd *ArchiveByDate) SetHookBeforArchive(f func(*StarLogger, string, string, os.FileInfo) error) {
abd.hookBefore = f
}
func (abd *ArchiveByDate) SetHookAfterArchive(f func(string, string, os.FileInfo) error) {
func (abd *ArchiveByDate) SetHookAfterArchive(f func(*StarLogger, string, string, os.FileInfo) error) {
abd.hookAfter = f
}
func NewArchiveByDate(archInterval int64, checkInterval int64, fileStyle string, hookbefor func(string, os.FileInfo) error, hookafter func(string, string, os.FileInfo) error) *ArchiveByDate {
func NewArchiveByDate(archInterval int64, checkInterval int64, baseFileName string, archiveFileName string, changeArchiveName bool, hookbefore func(*StarLogger, string, string, os.FileInfo) error, hookafter func(*StarLogger, string, string, os.FileInfo) error) *ArchiveByDate {
return &ArchiveByDate{
interval: archInterval,
checkInterval: checkInterval,
newFileNameStyle: fileStyle,
hookBefor: hookbefor,
hookAfter: hookafter,
interval: archInterval,
checkInterval: checkInterval,
changeArchiveName: changeArchiveName,
baseFileStyle: baseFileName,
archiveStyle: archiveFileName,
hookBefore: hookbefore,
hookAfter: hookafter,
}
}
type ArchiveBySize struct {
size int64
checkInterval int64
newFileNameStyle string
hookBefor func(string, os.FileInfo) error
hookAfter func(string, string, os.FileInfo) error
size int64
checkInterval int64
changeArchiveName bool
baseFileStyle string
archiveStyle string
hookBefore func(*StarLogger, string, string, os.FileInfo) error
hookAfter func(*StarLogger, string, string, os.FileInfo) error
}
func (abd *ArchiveBySize) ShouldArchiveNow(fullpath string, info os.FileInfo) bool {
func (abd *ArchiveBySize) ShouldArchiveNow(l *StarLogger, fullpath string, info os.FileInfo) bool {
if info.Size() > abd.size {
return true
}
return false
}
func (abd *ArchiveBySize) NextLogFilePath(oldpath string, info os.FileInfo) string {
func (abd *ArchiveBySize) NextLogFilePath(l *StarLogger, oldpath string, info os.FileInfo) string {
var newName string
dir := filepath.Dir(oldpath)
if !abd.changeArchiveName {
newName = abd.baseFileStyle + time.Now().Format(abd.archiveStyle)
} else {
newName = abd.baseFileStyle
}
return filepath.Join(dir, newName)
}
func (abd *ArchiveBySize) ArchiveLogFilePath(l *StarLogger, oldpath string, info os.FileInfo) string {
var newName string
dir := filepath.Dir(oldpath)
newName := time.Now().Format(abd.newFileNameStyle)
if abd.changeArchiveName {
newName = filepath.Base(abd.baseFileStyle) + time.Now().Format(abd.archiveStyle)
} else {
newName = abd.baseFileStyle
}
return filepath.Join(dir, newName)
}
@ -255,30 +310,117 @@ func (abd *ArchiveBySize) Interval() int64 {
return abd.checkInterval
}
func (abd *ArchiveBySize) HookBeforArchive() func(string, os.FileInfo) error {
return abd.hookBefor
func (abd *ArchiveBySize) HookBeforArchive() func(*StarLogger, string, string, os.FileInfo) error {
return abd.hookBefore
}
func (abd *ArchiveBySize) HookAfterArchive() func(string, string, os.FileInfo) error {
func (abd *ArchiveBySize) HookAfterArchive() func(*StarLogger, string, string, os.FileInfo) error {
return abd.hookAfter
}
func (abd *ArchiveBySize) SetHookBeforArchive(f func(string, os.FileInfo) error) {
abd.hookBefor = f
func (abd *ArchiveBySize) SetHookBeforArchive(f func(*StarLogger, string, string, os.FileInfo) error) {
abd.hookBefore = f
}
func (abd *ArchiveBySize) SetHookAfterArchive(f func(string, string, os.FileInfo) error) {
func (abd *ArchiveBySize) SetHookAfterArchive(f func(*StarLogger, string, string, os.FileInfo) error) {
abd.hookAfter = f
}
func NewArchiveBySize(size int64, checkInterval int64, fileStyle string, hookbefor func(string, os.FileInfo) error, hookafter func(string, string, os.FileInfo) error) *ArchiveBySize {
func NewArchiveBySize(size int64, checkInterval int64, baseFileStyle, archiveFileStyle string, changeArchiveFileName bool, hookbefore func(*StarLogger, string, string, os.FileInfo) error, hookafter func(*StarLogger, string, string, os.FileInfo) error) *ArchiveBySize {
return &ArchiveBySize{
size: size,
checkInterval: checkInterval,
newFileNameStyle: fileStyle,
hookBefor: hookbefor,
hookAfter: hookafter,
size: size,
checkInterval: checkInterval,
baseFileStyle: baseFileStyle,
archiveStyle: archiveFileStyle,
hookBefore: hookbefore,
hookAfter: hookafter,
changeArchiveName: changeArchiveFileName,
}
}
type ArchiveByDateSize struct {
interval int64
size int64
checkInterval int64
changeArchiveName bool
lastSwitchTime time.Time
baseFileStyle string
archiveStyle string
hookBefore func(*StarLogger, string, string, os.FileInfo) error
hookAfter func(*StarLogger, string, string, os.FileInfo) error
}
func (abd *ArchiveByDateSize) ShouldArchiveNow(l *StarLogger, fullpath string, info os.FileInfo) bool {
if abd.lastSwitchTime.IsZero() {
abd.lastSwitchTime = GetFileCreationTime(info)
}
if info.Size() > abd.size {
return true
}
sub := time.Now().Unix() - abd.lastSwitchTime.Unix()
if sub >= abd.interval || abd.interval-sub <= abd.checkInterval/2 {
return true
}
return false
}
func (abd *ArchiveByDateSize) NextLogFilePath(l *StarLogger, oldpath string, info os.FileInfo) string {
var newName string
dir := filepath.Dir(oldpath)
if !abd.changeArchiveName {
newName = abd.baseFileStyle + time.Now().Format(abd.archiveStyle)
} else {
newName = abd.baseFileStyle
}
return filepath.Join(dir, newName)
}
func (abd *ArchiveByDateSize) ArchiveLogFilePath(l *StarLogger, oldpath string, info os.FileInfo) string {
var newName string
dir := filepath.Dir(oldpath)
if abd.changeArchiveName {
newName = filepath.Base(abd.baseFileStyle) + time.Now().Format(abd.archiveStyle)
} else {
newName = abd.baseFileStyle
}
return filepath.Join(dir, newName)
}
func (abd *ArchiveByDateSize) Interval() int64 {
return abd.checkInterval
}
func (abd *ArchiveByDateSize) HookBeforArchive() func(*StarLogger, string, string, os.FileInfo) error {
return abd.hookBefore
}
func (abd *ArchiveByDateSize) HookAfterArchive() func(*StarLogger, string, string, os.FileInfo) error {
return func(logger *StarLogger, s string, s2 string, info os.FileInfo) error {
abd.lastSwitchTime = time.Now()
if abd.hookAfter != nil {
return abd.hookAfter(logger, s, s2, info)
}
return nil
}
}
func (abd *ArchiveByDateSize) SetHookBeforArchive(f func(*StarLogger, string, string, os.FileInfo) error) {
abd.hookBefore = f
}
func (abd *ArchiveByDateSize) SetHookAfterArchive(f func(*StarLogger, string, string, os.FileInfo) error) {
abd.hookAfter = f
}
func NewArchiveByDateSize(size int64, interval int64, checkInterval int64, baseFileStyle, archiveFileStyle string, changeArchiveFileName bool, hookbefore func(*StarLogger, string, string, os.FileInfo) error, hookafter func(*StarLogger, string, string, os.FileInfo) error) *ArchiveByDateSize {
return &ArchiveByDateSize{
size: size,
interval: interval,
checkInterval: checkInterval,
baseFileStyle: baseFileStyle,
archiveStyle: archiveFileStyle,
hookBefore: hookbefore,
hookAfter: hookafter,
changeArchiveName: changeArchiveFileName,
}
}

@ -0,0 +1,17 @@
package starlog
import (
"testing"
"time"
)
func TestArchiveByDate(t *testing.T) {
l := Std
SetLogFile("test.log", l, true)
StartArchive(l, NewArchiveByDateSize(4096, 24, 2, "test.log",
"_2006_01_02_15_04_05.log", true, nil, nil))
for {
time.Sleep(time.Second)
l.Infoln("hahaha", time.Now())
}
}

@ -8,8 +8,8 @@ import (
"strings"
"sync"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"b612.me/starlog/colorable"
"b612.me/starlog/isatty"
)
var (

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Yasuhiro Matsumoto
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -0,0 +1,48 @@
# go-colorable
[![Build Status](https://travis-ci.org/mattn/go-colorable.svg?branch=master)](https://travis-ci.org/mattn/go-colorable)
[![Codecov](https://codecov.io/gh/mattn/go-colorable/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-colorable)
[![GoDoc](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable)
[![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable)
Colorable writer for windows.
For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.)
This package is possible to handle escape sequence for ansi color on windows.
## Too Bad!
![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png)
## So Good!
![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png)
## Usage
```go
logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true})
logrus.SetOutput(colorable.NewColorableStdout())
logrus.Info("succeeded")
logrus.Warn("not correct")
logrus.Error("something error")
logrus.Fatal("panic")
```
You can compile above code on non-windows OSs.
## Installation
```
$ go get github.com/mattn/go-colorable
```
# License
MIT
# Author
Yasuhiro Matsumoto (a.k.a mattn)

@ -0,0 +1,37 @@
// +build appengine
package colorable
import (
"io"
"os"
_ "b612.me/starlog/isatty"
)
// NewColorable returns new instance of Writer which handles escape sequence.
func NewColorable(file *os.File) io.Writer {
if file == nil {
panic("nil passed instead of *os.File to NewColorable()")
}
return file
}
// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout.
func NewColorableStdout() io.Writer {
return os.Stdout
}
// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr.
func NewColorableStderr() io.Writer {
return os.Stderr
}
// EnableColorsStdout enable colors if possible.
func EnableColorsStdout(enabled *bool) func() {
if enabled != nil {
*enabled = true
}
return func() {}
}

@ -0,0 +1,38 @@
// +build !windows
// +build !appengine
package colorable
import (
"io"
"os"
_ "b612.me/starlog/isatty"
)
// NewColorable returns new instance of Writer which handles escape sequence.
func NewColorable(file *os.File) io.Writer {
if file == nil {
panic("nil passed instead of *os.File to NewColorable()")
}
return file
}
// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout.
func NewColorableStdout() io.Writer {
return os.Stdout
}
// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr.
func NewColorableStderr() io.Writer {
return os.Stderr
}
// EnableColorsStdout enable colors if possible.
func EnableColorsStdout(enabled *bool) func() {
if enabled != nil {
*enabled = true
}
return func() {}
}

@ -0,0 +1,98 @@
package colorable
import (
"bytes"
"os"
"runtime"
"testing"
)
// checkEncoding checks that colorable is output encoding agnostic as long as
// the encoding is a superset of ASCII. This implies that one byte not part of
// an ANSI sequence must give exactly one byte in output
func checkEncoding(t *testing.T, data []byte) {
// Send non-UTF8 data to colorable
b := bytes.NewBuffer(make([]byte, 0, 10))
if b.Len() != 0 {
t.FailNow()
}
// TODO move colorable wrapping outside the test
NewNonColorable(b).Write(data)
if b.Len() != len(data) {
t.Fatalf("%d bytes expected, got %d", len(data), b.Len())
}
}
func TestEncoding(t *testing.T) {
checkEncoding(t, []byte{}) // Empty
checkEncoding(t, []byte(`abc`)) // "abc"
checkEncoding(t, []byte(`é`)) // "é" in UTF-8
checkEncoding(t, []byte{233}) // 'é' in Latin-1
}
func TestNonColorable(t *testing.T) {
var buf bytes.Buffer
want := "hello"
NewNonColorable(&buf).Write([]byte("\x1b[0m" + want + "\x1b[2J"))
got := buf.String()
if got != "hello" {
t.Fatalf("want %q but %q", want, got)
}
buf.Reset()
NewNonColorable(&buf).Write([]byte("\x1b["))
got = buf.String()
if got != "" {
t.Fatalf("want %q but %q", "", got)
}
}
func TestNonColorableNil(t *testing.T) {
paniced := false
func() {
defer func() {
recover()
paniced = true
}()
NewNonColorable(nil)
NewColorable(nil)
}()
if !paniced {
t.Fatalf("should panic")
}
}
func TestNonColorableESC(t *testing.T) {
var b bytes.Buffer
NewNonColorable(&b).Write([]byte{0x1b})
if b.Len() > 0 {
t.Fatalf("0 bytes expected, got %d", b.Len())
}
}
func TestNonColorableBadESC(t *testing.T) {
var b bytes.Buffer
NewNonColorable(&b).Write([]byte{0x1b, 0x1b})
if b.Len() > 0 {
t.Fatalf("0 bytes expected, got %d", b.Len())
}
}
func TestColorable(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skipf("skip this test on windows")
}
_, ok := NewColorableStdout().(*os.File)
if !ok {
t.Fatalf("should os.Stdout on UNIX")
}
_, ok = NewColorableStderr().(*os.File)
if !ok {
t.Fatalf("should os.Stdout on UNIX")
}
_, ok = NewColorable(os.Stdout).(*os.File)
if !ok {
t.Fatalf("should os.Stdout on UNIX")
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -e
echo "" > coverage.txt
for d in $(go list ./... | grep -v vendor); do
go test -race -coverprofile=profile.out -covermode=atomic "$d"
if [ -f profile.out ]; then
cat profile.out >> coverage.txt
rm profile.out
fi
done

@ -0,0 +1,55 @@
package colorable
import (
"bytes"
"io"
)
// NonColorable holds writer but removes escape sequence.
type NonColorable struct {
out io.Writer
}
// NewNonColorable returns new instance of Writer which removes escape sequence from Writer.
func NewNonColorable(w io.Writer) io.Writer {
return &NonColorable{out: w}
}
// Write writes data on console
func (w *NonColorable) Write(data []byte) (n int, err error) {
er := bytes.NewReader(data)
var bw [1]byte
loop:
for {
c1, err := er.ReadByte()
if err != nil {
break loop
}
if c1 != 0x1b {
bw[0] = c1
w.out.Write(bw[:])
continue
}
c2, err := er.ReadByte()
if err != nil {
break loop
}
if c2 != 0x5b {
continue
}
var buf bytes.Buffer
for {
c, err := er.ReadByte()
if err != nil {
break loop
}
if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' {
break
}
buf.Write([]byte(string(c)))
}
}
return len(data), nil
}

@ -35,7 +35,7 @@ func generateCoreLogStr(skip int, logstr string) string {
return logStr
}
func (logger *starlog) build(thread string, isStd bool, handler func([]Attr, string), level int, logDetail string) {
func (logger *starlog) build(thread string, isStd bool, isShow bool, handler func(data LogData), level int, logDetail string) {
logger.mu.Lock()
defer logger.mu.Unlock()
var skip, line int = 3, 0
@ -60,32 +60,53 @@ func (logger *starlog) build(thread string, isStd bool, handler func([]Attr, str
h, i, s := now.Clock()
micro := now.Nanosecond() / 1e3
logStr := fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d.%06d", y, m, d, h, i, s, micro)
var cenStr string
if logger.showDeatilFile {
logStr += " " + fileName + ":" + strconv.Itoa(line)
cenStr += " " + fileName + ":" + strconv.Itoa(line)
}
if logger.showFuncName {
logStr += " <" + funcname + ">"
cenStr += " <" + funcname + ">"
}
if logger.showThread {
logStr += " |" + thread + "|"
cenStr += " |" + thread + "|"
}
if logger.showLevel {
logStr += " " + `[` + levels[level] + `]`
cenStr += " " + `[` + levels[level] + `]`
}
logStr += " " + logDetail
if logger.showStd {
if !logger.showColor || !logger.onlyColorLevel {
logStr += cenStr + " " + logDetail
} else {
logStr += logger.colorMe[level].Sprint(cenStr) + " " + logDetail
}
if isShow {
if !logger.showColor {
fmt.Print(logStr)
if level >= logger.errOutputLevel {
fmt.Fprint(os.Stderr, logStr)
} else {
fmt.Print(logStr)
}
} else if !logger.onlyColorLevel {
if level < logger.errOutputLevel {
logger.colorMe[level].Fprint(stdScreen, logStr)
} else {
logger.colorMe[level].Fprint(errScreen, logStr)
}
} else {
//logcolor := NewColor(logger.colorList[level]...)
logger.colorMe[level].Fprint(stdScreen, logStr)
if level < logger.errOutputLevel {
fmt.Fprint(stdScreen, logStr)
} else {
fmt.Fprint(errScreen, logStr)
}
}
}
if handler != nil {
stacks.Push(logTransfer{
handlerFunc: handler,
colors: logger.colorList[level],
logStr: logStr,
LogData: LogData{
Log: logStr,
Colors: logger.colorList[level],
Name: logger.name,
},
})
}
if !logger.stopWriter {
@ -123,152 +144,182 @@ func (logger *starlog) println(str ...interface{}) string {
return fmt.Sprintln(str...)
}
func (logger *starlog) Debug(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Debug(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
logger.build(thread, isStd, handler, LvDebug, strs)
logger.build(thread, isStd, logger.showStd, handler, LvDebug, strs)
}
func (logger *starlog) Debugf(thread string, isStd bool, handler func([]Attr, string), format string, str ...interface{}) {
func (logger *starlog) Debugf(thread string, isStd bool, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.build(thread, isStd, handler, LvDebug, strs)
logger.build(thread, isStd, logger.showStd, handler, LvDebug, strs)
}
func (logger *starlog) Debugln(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Debugln(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.build(thread, isStd, handler, LvDebug, strs)
logger.build(thread, isStd, logger.showStd, handler, LvDebug, strs)
}
func (logger *starlog) Info(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Info(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
logger.build(thread, isStd, handler, LvInfo, strs)
logger.build(thread, isStd, logger.showStd, handler, LvInfo, strs)
}
func (logger *starlog) Infof(thread string, isStd bool, handler func([]Attr, string), format string, str ...interface{}) {
func (logger *starlog) Infof(thread string, isStd bool, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.build(thread, isStd, handler, LvInfo, strs)
logger.build(thread, isStd, logger.showStd, handler, LvInfo, strs)
}
func (logger *starlog) Infoln(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Infoln(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.build(thread, isStd, handler, LvInfo, strs)
logger.build(thread, isStd, logger.showStd, handler, LvInfo, strs)
}
func (logger *starlog) Notice(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Notice(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
logger.build(thread, isStd, handler, LvNotice, strs)
logger.build(thread, isStd, logger.showStd, handler, LvNotice, strs)
}
func (logger *starlog) Noticef(thread string, isStd bool, handler func([]Attr, string), format string, str ...interface{}) {
func (logger *starlog) Noticef(thread string, isStd bool, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.build(thread, isStd, handler, LvNotice, strs)
logger.build(thread, isStd, logger.showStd, handler, LvNotice, strs)
}
func (logger *starlog) Noticeln(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Noticeln(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.build(thread, isStd, handler, LvNotice, strs)
logger.build(thread, isStd, logger.showStd, handler, LvNotice, strs)
}
func (logger *starlog) Warning(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Warning(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
logger.build(thread, isStd, handler, LvWarning, strs)
logger.build(thread, isStd, logger.showStd, handler, LvWarning, strs)
}
func (logger *starlog) Warningf(thread string, isStd bool, handler func([]Attr, string), format string, str ...interface{}) {
func (logger *starlog) Warningf(thread string, isStd bool, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.build(thread, isStd, handler, LvWarning, strs)
logger.build(thread, isStd, logger.showStd, handler, LvWarning, strs)
}
func (logger *starlog) Warningln(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Warningln(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.build(thread, isStd, handler, LvWarning, strs)
logger.build(thread, isStd, logger.showStd, handler, LvWarning, strs)
}
func (logger *starlog) Error(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Error(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
logger.build(thread, isStd, handler, LvError, strs)
logger.build(thread, isStd, logger.showStd, handler, LvError, strs)
}
func (logger *starlog) Errorf(thread string, isStd bool, handler func([]Attr, string), format string, str ...interface{}) {
func (logger *starlog) Errorf(thread string, isStd bool, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.build(thread, isStd, handler, LvError, strs)
logger.build(thread, isStd, logger.showStd, handler, LvError, strs)
}
func (logger *starlog) Errorln(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Errorln(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.build(thread, isStd, handler, LvError, strs)
logger.build(thread, isStd, logger.showStd, handler, LvError, strs)
}
func (logger *starlog) Critical(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Critical(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
logger.build(thread, isStd, handler, LvCritical, strs)
logger.build(thread, isStd, logger.showStd, handler, LvCritical, strs)
}
func (logger *starlog) Criticalf(thread string, isStd bool, handler func([]Attr, string), format string, str ...interface{}) {
func (logger *starlog) Criticalf(thread string, isStd bool, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.build(thread, isStd, handler, LvCritical, strs)
logger.build(thread, isStd, logger.showStd, handler, LvCritical, strs)
}
func (logger *starlog) Criticalln(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Criticalln(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.build(thread, isStd, handler, LvCritical, strs)
logger.build(thread, isStd, logger.showStd, handler, LvCritical, strs)
}
func (logger *starlog) Fatal(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Fatal(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
logger.build(thread, isStd, handler, LvFatal, strs)
logger.build(thread, isStd, logger.showStd, handler, LvFatal, strs)
os.Exit(9)
}
func (logger *starlog) Fatalf(thread string, isStd bool, handler func([]Attr, string), format string, str ...interface{}) {
func (logger *starlog) Fatalf(thread string, isStd bool, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.build(thread, isStd, handler, LvFatal, strs)
logger.build(thread, isStd, logger.showStd, handler, LvFatal, strs)
os.Exit(9)
}
func (logger *starlog) Fatalln(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Fatalln(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.build(thread, isStd, handler, LvFatal, strs)
logger.build(thread, isStd, logger.showStd, handler, LvFatal, strs)
os.Exit(9)
}
func (logger *starlog) Panic(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Panic(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
logger.build(thread, isStd, handler, LvPanic, strs)
logger.build(thread, isStd, logger.showStd, handler, LvPanic, strs)
panic(str)
}
func (logger *starlog) Panicf(thread string, isStd bool, handler func([]Attr, string), format string, str ...interface{}) {
func (logger *starlog) Panicf(thread string, isStd bool, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.build(thread, isStd, handler, LvPanic, strs)
logger.build(thread, isStd, logger.showStd, handler, LvPanic, strs)
panic(fmt.Sprintf(format, str...))
}
func (logger *starlog) Panicln(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Panicln(thread string, isStd bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.build(thread, isStd, handler, LvPanic, strs)
logger.build(thread, isStd, logger.showStd, handler, LvPanic, strs)
panic(fmt.Sprintln(str...))
}
func (logger *starlog) Print(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Print(thread string, isStd bool, isShow bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
if logger.showStd {
if isShow {
fmt.Print(strs)
}
logger.write(strs)
}
func (logger *starlog) Printf(thread string, isStd bool, handler func([]Attr, string), format string, str ...interface{}) {
func (logger *starlog) Printf(thread string, isStd bool, isShow bool, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
if logger.showStd {
if isShow {
fmt.Print(strs)
}
logger.write(strs)
}
func (logger *starlog) Println(thread string, isStd bool, handler func([]Attr, string), str ...interface{}) {
func (logger *starlog) Println(thread string, isStd bool, isShow bool, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
if logger.showStd {
if isShow {
fmt.Print(strs)
}
logger.write(strs)
}
func (logger *starlog) Log(thread string, isStd bool, isShow bool, level int, handler func(LogData), str ...interface{}) {
strs := fmt.Sprint(str...)
logger.build(thread, isStd, isShow, handler, level, strs)
}
func (logger *starlog) Logf(thread string, isStd bool, isShow bool, level int, handler func(LogData), format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.build(thread, isStd, isShow, handler, level, strs)
}
func (logger *starlog) Logln(thread string, isStd bool, isShow bool, level int, handler func(LogData), str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.build(thread, isStd, isShow, handler, level, strs)
}
func (logger *starlog) Write(str ...interface{}) {
strs := fmt.Sprint(str...)
logger.Write(strs)
}
func (logger *starlog) Writef(format string, str ...interface{}) {
strs := fmt.Sprintf(format, str...)
logger.Write(strs)
}
func (logger *starlog) Writeln(str ...interface{}) {
strs := fmt.Sprintln(str...)
logger.Write(strs)
}

@ -0,0 +1,34 @@
package starlog
import (
"os"
)
// 检测文件/文件夹是否存在
func Exists(path string) bool {
_, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
// IsFile 返回给定文件地址是否是一个文件,
// True为是一个文件,False为不是文件或路径无效
func IsFile(fpath string) bool {
s, err := os.Stat(fpath)
if err != nil {
return false
}
return !s.IsDir()
}
// IsFolder 返回给定文件地址是否是一个文件夹,
// True为是一个文件夹,False为不是文件夹或路径无效
func IsFolder(fpath string) bool {
s, err := os.Stat(fpath)
if err != nil {
return false
}
return s.IsDir()
}

@ -0,0 +1,22 @@
//go:build darwin
// +build darwin
package starlog
import (
"os"
"syscall"
"time"
)
func timespecToTime(ts syscall.Timespec) time.Time {
return time.Unix(int64(ts.Sec), int64(ts.Nsec))
}
func GetFileCreationTime(fileinfo os.FileInfo) time.Time {
return timespecToTime(fileinfo.Sys().(*syscall.Stat_t).Ctimespec)
}
func GetFileAccessTime(fileinfo os.FileInfo) time.Time {
return timespecToTime(fileinfo.Sys().(*syscall.Stat_t).Atimespec)
}

@ -0,0 +1,22 @@
//go:build linux
// +build linux
package starlog
import (
"os"
"syscall"
"time"
)
func timespecToTime(ts syscall.Timespec) time.Time {
return time.Unix(int64(ts.Sec), int64(ts.Nsec))
}
func GetFileCreationTime(fileinfo os.FileInfo) time.Time {
return timespecToTime(fileinfo.Sys().(*syscall.Stat_t).Ctim)
}
func GetFileAccessTime(fileinfo os.FileInfo) time.Time {
return timespecToTime(fileinfo.Sys().(*syscall.Stat_t).Atim)
}

@ -0,0 +1,20 @@
//go:build windows
// +build windows
package starlog
import (
"os"
"syscall"
"time"
)
func GetFileCreationTime(fileinfo os.FileInfo) time.Time {
d := fileinfo.Sys().(*syscall.Win32FileAttributeData)
return time.Unix(0, d.CreationTime.Nanoseconds())
}
func GetFileAccessTime(fileinfo os.FileInfo) time.Time {
d := fileinfo.Sys().(*syscall.Win32FileAttributeData)
return time.Unix(0, d.LastAccessTime.Nanoseconds())
}

@ -0,0 +1,5 @@
module b612.me/starlog
go 1.16
require golang.org/x/sys v0.24.0

@ -0,0 +1,2 @@
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

@ -0,0 +1,9 @@
Copyright (c) Yasuhiro MATSUMOTO <mattn.jp@gmail.com>
MIT License (Expat)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -0,0 +1,50 @@
# go-isatty
[![Godoc Reference](https://godoc.org/github.com/mattn/go-isatty?status.svg)](http://godoc.org/github.com/mattn/go-isatty)
[![Codecov](https://codecov.io/gh/mattn/go-isatty/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-isatty)
[![Coverage Status](https://coveralls.io/repos/github/mattn/go-isatty/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-isatty?branch=master)
[![Go Report Card](https://goreportcard.com/badge/mattn/go-isatty)](https://goreportcard.com/report/mattn/go-isatty)
isatty for golang
## Usage
```go
package main
import (
"fmt"
"github.com/mattn/go-isatty"
"os"
)
func main() {
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println("Is Terminal")
} else if isatty.IsCygwinTerminal(os.Stdout.Fd()) {
fmt.Println("Is Cygwin/MSYS2 Terminal")
} else {
fmt.Println("Is Not Terminal")
}
}
```
## Installation
```
$ go get github.com/mattn/go-isatty
```
## License
MIT
## Author
Yasuhiro Matsumoto (a.k.a mattn)
## Thanks
* k-takata: base idea for IsCygwinTerminal
https://github.com/k-takata/go-iscygpty

@ -0,0 +1,2 @@
// Package isatty implements interface to isatty
package isatty

@ -0,0 +1,18 @@
package isatty_test
import (
"fmt"
"os"
"b612.me/starlog/isatty"
)
func Example() {
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println("Is Terminal")
} else if isatty.IsCygwinTerminal(os.Stdout.Fd()) {
fmt.Println("Is Cygwin/MSYS2 Terminal")
} else {
fmt.Println("Is Not Terminal")
}
}

@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -e
echo "" > coverage.txt
for d in $(go list ./... | grep -v vendor); do
go test -race -coverprofile=profile.out -covermode=atomic "$d"
if [ -f profile.out ]; then
cat profile.out >> coverage.txt
rm profile.out
fi
done

@ -0,0 +1,18 @@
// +build darwin freebsd openbsd netbsd dragonfly
// +build !appengine
package isatty
import "golang.org/x/sys/unix"
// IsTerminal return true if the file descriptor is terminal.
func IsTerminal(fd uintptr) bool {
_, err := unix.IoctlGetTermios(int(fd), unix.TIOCGETA)
return err == nil
}
// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2
// terminal. This is also always false on this environment.
func IsCygwinTerminal(fd uintptr) bool {
return false
}

@ -0,0 +1,15 @@
// +build appengine js nacl wasm
package isatty
// IsTerminal returns true if the file descriptor is terminal which
// is always false on js and appengine classic which is a sandboxed PaaS.
func IsTerminal(fd uintptr) bool {
return false
}
// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2
// terminal. This is also always false on this environment.
func IsCygwinTerminal(fd uintptr) bool {
return false
}

@ -0,0 +1,19 @@
// +build !windows
package isatty
import (
"os"
"testing"
)
func TestTerminal(t *testing.T) {
// test for non-panic
IsTerminal(os.Stdout.Fd())
}
func TestCygwinPipeName(t *testing.T) {
if IsCygwinTerminal(os.Stdout.Fd()) {
t.Fatal("should be false always")
}
}

@ -0,0 +1,22 @@
// +build plan9
package isatty
import (
"syscall"
)
// IsTerminal returns true if the given file descriptor is a terminal.
func IsTerminal(fd uintptr) bool {
path, err := syscall.Fd2path(int(fd))
if err != nil {
return false
}
return path == "/dev/cons" || path == "/mnt/term/dev/cons"
}
// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2
// terminal. This is also always false on this environment.
func IsCygwinTerminal(fd uintptr) bool {
return false
}

@ -0,0 +1,22 @@
// +build solaris
// +build !appengine
package isatty
import (
"golang.org/x/sys/unix"
)
// IsTerminal returns true if the given file descriptor is a terminal.
// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c
func IsTerminal(fd uintptr) bool {
var termio unix.Termio
err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio)
return err == nil
}
// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2
// terminal. This is also always false on this environment.
func IsCygwinTerminal(fd uintptr) bool {
return false
}

@ -0,0 +1,18 @@
// +build linux aix
// +build !appengine
package isatty
import "golang.org/x/sys/unix"
// IsTerminal return true if the file descriptor is terminal.
func IsTerminal(fd uintptr) bool {
_, err := unix.IoctlGetTermios(int(fd), unix.TCGETS)
return err == nil
}
// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2
// terminal. This is also always false on this environment.
func IsCygwinTerminal(fd uintptr) bool {
return false
}

@ -0,0 +1,125 @@
// +build windows
// +build !appengine
package isatty
import (
"errors"
"strings"
"syscall"
"unicode/utf16"
"unsafe"
)
const (
objectNameInfo uintptr = 1
fileNameInfo = 2
fileTypePipe = 3
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
ntdll = syscall.NewLazyDLL("ntdll.dll")
procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx")
procGetFileType = kernel32.NewProc("GetFileType")
procNtQueryObject = ntdll.NewProc("NtQueryObject")
)
func init() {
// Check if GetFileInformationByHandleEx is available.
if procGetFileInformationByHandleEx.Find() != nil {
procGetFileInformationByHandleEx = nil
}
}
// IsTerminal return true if the file descriptor is terminal.
func IsTerminal(fd uintptr) bool {
var st uint32
r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0)
return r != 0 && e == 0
}
// Check pipe name is used for cygwin/msys2 pty.
// Cygwin/MSYS2 PTY has a name like:
// \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master
func isCygwinPipeName(name string) bool {
token := strings.Split(name, "-")
if len(token) < 5 {
return false
}
if token[0] != `\msys` &&
token[0] != `\cygwin` &&
token[0] != `\Device\NamedPipe\msys` &&
token[0] != `\Device\NamedPipe\cygwin` {
return false
}
if token[1] == "" {
return false
}
if !strings.HasPrefix(token[2], "pty") {
return false
}
if token[3] != `from` && token[3] != `to` {
return false
}
if token[4] != "master" {
return false
}
return true
}
// getFileNameByHandle use the undocomented ntdll NtQueryObject to get file full name from file handler
// since GetFileInformationByHandleEx is not avilable under windows Vista and still some old fashion
// guys are using Windows XP, this is a workaround for those guys, it will also work on system from
// Windows vista to 10
// see https://stackoverflow.com/a/18792477 for details
func getFileNameByHandle(fd uintptr) (string, error) {
if procNtQueryObject == nil {
return "", errors.New("ntdll.dll: NtQueryObject not supported")
}
var buf [4 + syscall.MAX_PATH]uint16
var result int
r, _, e := syscall.Syscall6(procNtQueryObject.Addr(), 5,
fd, objectNameInfo, uintptr(unsafe.Pointer(&buf)), uintptr(2*len(buf)), uintptr(unsafe.Pointer(&result)), 0)
if r != 0 {
return "", e
}
return string(utf16.Decode(buf[4 : 4+buf[0]/2])), nil
}
// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2
// terminal.
func IsCygwinTerminal(fd uintptr) bool {
if procGetFileInformationByHandleEx == nil {
name, err := getFileNameByHandle(fd)
if err != nil {
return false
}
return isCygwinPipeName(name)
}
// Cygwin/msys's pty is a pipe.
ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0)
if ft != fileTypePipe || e != 0 {
return false
}
var buf [2 + syscall.MAX_PATH]uint16
r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(),
4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)),
uintptr(len(buf)*2), 0, 0)
if r == 0 || e != 0 {
return false
}
l := *(*uint32)(unsafe.Pointer(&buf))
return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2])))
}

@ -0,0 +1,38 @@
// +build windows
package isatty
import (
"testing"
)
func TestCygwinPipeName(t *testing.T) {
tests := []struct {
name string
result bool
}{
{``, false},
{`\msys-`, false},
{`\cygwin-----`, false},
{`\msys-x-PTY5-pty1-from-master`, false},
{`\cygwin-x-PTY5-from-master`, false},
{`\cygwin-x-pty2-from-toaster`, false},
{`\cygwin--pty2-from-master`, false},
{`\\cygwin-x-pty2-from-master`, false},
{`\cygwin-x-pty2-from-master-`, true}, // for the feature
{`\cygwin-e022582115c10879-pty4-from-master`, true},
{`\msys-e022582115c10879-pty4-to-master`, true},
{`\cygwin-e022582115c10879-pty4-to-master`, true},
{`\Device\NamedPipe\cygwin-e022582115c10879-pty4-from-master`, true},
{`\Device\NamedPipe\msys-e022582115c10879-pty4-to-master`, true},
{`Device\NamedPipe\cygwin-e022582115c10879-pty4-to-master`, false},
}
for _, test := range tests {
want := test.result
got := isCygwinPipeName(test.name)
if want != got {
t.Fatalf("isatty(%q): got %v, want %v:", test.name, got, want)
}
}
}

@ -0,0 +1,149 @@
package starlog
import (
"errors"
"io"
"os"
"sync"
"sync/atomic"
)
type starMapKV struct {
kvMap map[interface{}]interface{}
mu sync.RWMutex
}
func newStarMap() starMapKV {
var mp starMapKV
mp.kvMap = make(map[interface{}]interface{})
return mp
}
func (m *starMapKV) Get(key interface{}) (interface{}, error) {
var err error
m.mu.RLock()
defer m.mu.RUnlock()
data, ok := m.kvMap[key]
if !ok {
err = os.ErrNotExist
}
return data, err
}
func (m *starMapKV) MustGet(key interface{}) interface{} {
result, _ := m.Get(key)
return result
}
func (m *starMapKV) Store(key interface{}, value interface{}) error {
m.mu.Lock()
defer m.mu.Unlock()
m.kvMap[key] = value
return nil
}
func (m *starMapKV) Exists(key interface{}) bool {
m.mu.RLock()
defer m.mu.RUnlock()
_, ok := m.kvMap[key]
return ok
}
func (m *starMapKV) Delete(key interface{}) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.kvMap, key)
return nil
}
func (m *starMapKV) Range(run func(k interface{}, v interface{}) bool) error {
for k, v := range m.kvMap {
if !run(k, v) {
break
}
}
return nil
}
type starChanStack struct {
data chan interface{}
cap uint64
current uint64
isClose atomic.Value
}
func newStarChanStack(cap uint64) *starChanStack {
rtnBuffer := new(starChanStack)
rtnBuffer.cap = cap
rtnBuffer.isClose.Store(false)
rtnBuffer.data = make(chan interface{}, cap)
return rtnBuffer
}
func (s *starChanStack) init() {
s.cap = 1024
s.data = make(chan interface{}, s.cap)
s.isClose.Store(false)
}
func (s *starChanStack) Free() uint64 {
return s.cap - s.current
}
func (s *starChanStack) Cap() uint64 {
return s.cap
}
func (s *starChanStack) Len() uint64 {
return s.current
}
func (s *starChanStack) Pop() (interface{}, error) {
if s.isClose.Load() == nil {
s.init()
}
if s.isClose.Load().(bool) {
return 0, io.EOF
}
data, ok := <-s.data
if !ok {
s.isClose.Store(true)
return 0, errors.New("channel read error")
}
for {
current := atomic.LoadUint64(&s.current)
if atomic.CompareAndSwapUint64(&s.current, current, current-1) {
break
}
}
return data, nil
}
func (s *starChanStack) Push(data interface{}) error {
defer func() {
recover()
}()
if s.isClose.Load() == nil {
s.init()
}
if s.isClose.Load().(bool) {
return io.EOF
}
s.data <- data
for {
current := atomic.LoadUint64(&s.current)
if atomic.CompareAndSwapUint64(&s.current, current, current+1) {
break
}
}
return nil
}
func (s *starChanStack) Close() error {
if s.isClose.Load() == nil {
s.init()
}
s.isClose.Store(true)
close(s.data)
return nil
}

@ -14,7 +14,6 @@ var stdmu sync.Mutex
func init() {
rand.Seed(time.Now().UnixNano())
stackStopChan = make(chan int)
StartStacks()
Std = NewStarlog(nil)
}
@ -214,6 +213,30 @@ func Println(str ...interface{}) {
Std.Println(str...)
}
func Log(isShow bool, level int, str ...interface{}) {
stdmu.Lock()
defer stdmu.Unlock()
Std.isStd = true
Std.Log(isShow, level, str...)
Std.isStd = false
}
func Logf(isShow bool, level int, format string, str ...interface{}) {
stdmu.Lock()
defer stdmu.Unlock()
Std.isStd = true
Std.Logf(isShow, level, format, str...)
Std.isStd = false
}
func Logln(isShow bool, level int, str ...interface{}) {
stdmu.Lock()
defer stdmu.Unlock()
Std.isStd = true
Std.Logln(isShow, level, str...)
Std.isStd = false
}
func StdPrint(attr []Attr, str ...interface{}) {
strs := fmt.Sprint(str...)
NewColor(attr...).Fprint(stdScreen, strs)
@ -236,10 +259,10 @@ func GetWriter() io.Writer {
return Std.GetWriter()
}
func SetHandler(f func([]Attr, string)) {
func SetHandler(f func(LogData)) {
Std.SetHandler(f)
}
func GetHandler() func([]Attr, string) {
func GetHandler() func(LogData) {
return Std.GetHandler()
}
func SetSwitching(sw bool) {

@ -28,16 +28,26 @@ func (logger *StarLogger) GetWriter() io.Writer {
return logger.logcore.output
}
func (logger *StarLogger) SetHandler(f func([]Attr, string)) {
func (logger *StarLogger) SetHandler(f func(LogData)) {
if f != nil {
StartStacks()
}
logger.handlerFunc = f
}
func (logger *StarLogger) GetHandler() func([]Attr, string) {
func (logger *StarLogger) GetHandler() func(LogData) {
return logger.handlerFunc
}
func (logger *StarLogger) SetSwitching(sw bool) {
logger.logcore.switching = sw
}
func (logger *StarLogger) SetOnlyColorLevel(ocl bool) {
logger.logcore.onlyColorLevel = ocl
}
func (logger *StarLogger) GetOnlyColorLevel() bool {
return logger.logcore.onlyColorLevel
}
func (logger *StarLogger) SetShowOriginFile(val bool) {
logger.logcore.showDeatilFile = val
}
@ -175,13 +185,37 @@ func (logger *StarLogger) Fatalln(str ...interface{}) {
}
func (logger *StarLogger) Print(str ...interface{}) {
logger.logcore.Print(logger.thread, logger.isStd, logger.handlerFunc, str...)
logger.logcore.Print(logger.thread, logger.isStd, logger.GetShowStd(), logger.handlerFunc, str...)
}
func (logger *StarLogger) Printf(format string, str ...interface{}) {
logger.logcore.Printf(logger.thread, logger.isStd, logger.handlerFunc, format, str...)
logger.logcore.Printf(logger.thread, logger.isStd, logger.GetShowStd(), logger.handlerFunc, format, str...)
}
func (logger *StarLogger) Println(str ...interface{}) {
logger.logcore.Println(logger.thread, logger.isStd, logger.handlerFunc, str...)
logger.logcore.Println(logger.thread, logger.isStd, logger.GetShowStd(), logger.handlerFunc, str...)
}
func (logger *StarLogger) Log(showLog bool, level int, str ...interface{}) {
logger.logcore.Log(logger.thread, logger.isStd, showLog, level, logger.handlerFunc, str...)
}
func (logger *StarLogger) Logf(showLog bool, level int, format string, str ...interface{}) {
logger.logcore.Logf(logger.thread, logger.isStd, showLog, level, logger.handlerFunc, format, str...)
}
func (logger *StarLogger) Logln(showLog bool, level int, str ...interface{}) {
logger.logcore.Logln(logger.thread, logger.isStd, showLog, level, logger.handlerFunc, str...)
}
func (logger *StarLogger) Write(str ...interface{}) {
logger.logcore.Write(str...)
}
func (logger *StarLogger) Writef(format string, str ...interface{}) {
logger.logcore.Writef(format, str...)
}
func (logger *StarLogger) Writeln(str ...interface{}) {
logger.logcore.Writeln(str...)
}

@ -7,8 +7,7 @@ import (
"sync"
"time"
"b612.me/starmap"
"github.com/mattn/go-colorable"
"b612.me/starlog/colorable"
)
const (
@ -33,15 +32,18 @@ var (
LvPanic: "PANIC",
LvFatal: "FATAL",
}
stacks starmap.StarStack
stacks *starChanStack
stackStarted bool = false
stackStopChan chan int
stackMu sync.Mutex
stdScreen io.Writer = colorable.NewColorableStdout()
errScreen io.Writer = colorable.NewColorableStderr()
)
type starlog struct {
mu *sync.Mutex
output io.Writer
errOutputLevel int
showFuncName bool
showThread bool
showLevel bool
@ -49,30 +51,37 @@ type starlog struct {
showColor bool
switching bool
showStd bool
onlyColorLevel bool
stopWriter bool
id string
colorList map[int][]Attr
colorMe map[int]*Color
name string
colorList map[int][]Attr
colorMe map[int]*Color
}
type StarLogger struct {
thread string
handlerFunc func([]Attr, string)
handlerFunc func(LogData)
logcore *starlog
isStd bool
}
type logTransfer struct {
handlerFunc func([]Attr, string)
colors []Attr
logStr string
handlerFunc func(LogData)
LogData
}
type LogData struct {
Name string
Log string
Colors []Attr
}
func newLogCore(out io.Writer) *starlog {
return &starlog{
mu: &sync.Mutex{},
output: out,
errOutputLevel: LvError,
showFuncName: true,
showThread: true,
showLevel: true,
@ -85,7 +94,7 @@ func newLogCore(out io.Writer) *starlog {
colorList: map[int][]Attr{
LvDebug: []Attr{FgWhite},
LvInfo: []Attr{FgGreen},
LvNotice: []Attr{FgBlue},
LvNotice: []Attr{FgCyan},
LvWarning: []Attr{FgYellow},
LvError: []Attr{FgMagenta},
LvCritical: []Attr{FgRed, Bold},
@ -95,7 +104,7 @@ func newLogCore(out io.Writer) *starlog {
colorMe: map[int]*Color{
LvDebug: NewColor([]Attr{FgWhite}...),
LvInfo: NewColor([]Attr{FgGreen}...),
LvNotice: NewColor([]Attr{FgBlue}...),
LvNotice: NewColor([]Attr{FgCyan}...),
LvWarning: NewColor([]Attr{FgYellow}...),
LvError: NewColor([]Attr{FgMagenta}...),
LvCritical: NewColor([]Attr{FgRed, Bold}...),
@ -114,6 +123,18 @@ func NewStarlog(out io.Writer) *StarLogger {
}
}
func (logger *StarLogger) StdErrLevel() int {
logger.logcore.mu.Lock()
defer logger.logcore.mu.Unlock()
return logger.logcore.errOutputLevel
}
func (logger *StarLogger) SetStdErrLevel(level int) {
logger.logcore.mu.Lock()
defer logger.logcore.mu.Unlock()
logger.logcore.errOutputLevel = level
}
func (logger *StarLogger) NewFlag() *StarLogger {
return &StarLogger{
thread: getRandomFlag(false),
@ -126,6 +147,16 @@ func (logger *StarLogger) SetNewRandomFlag() {
logger.thread = getRandomFlag(false)
}
func (logger *StarLogger) SetName(name string) {
logger.logcore.mu.Lock()
defer logger.logcore.mu.Unlock()
logger.logcore.name = name
}
func (logger *StarLogger) GetName() string {
return logger.logcore.name
}
func getRandomFlag(isMain bool) string {
rand.Seed(time.Now().UnixNano())
if isMain {
@ -144,11 +175,17 @@ func generateId() string {
}
func StartStacks() {
stackMu.Lock()
if stackStarted {
stackMu.Unlock()
return
}
unlock := make(chan struct{})
go func() {
stackStarted = true
stacks = newStarChanStack(1024)
stackMu.Unlock()
unlock <- struct{}{}
defer func() {
stackStarted = false
}()
@ -158,17 +195,17 @@ func StartStacks() {
return
default:
}
poped := stacks.MustPop()
if poped == nil {
time.Sleep(time.Millisecond * 10)
continue
poped, err := stacks.Pop()
if err != nil {
return
}
val := poped.(logTransfer)
if val.handlerFunc != nil {
val.handlerFunc(val.colors, val.logStr)
val.handlerFunc(val.LogData)
}
}
}()
<-unlock
}
func StopStacks() {
@ -177,3 +214,8 @@ func StopStacks() {
}
stackStopChan <- 1
}
func Stop() {
stacks.Close()
StopStacks()
}

Loading…
Cancel
Save