Skip to content

Commit

Permalink
fix #117: add a log level setting
Browse files Browse the repository at this point in the history
  • Loading branch information
evanw committed May 26, 2020
1 parent 467b22d commit 6dc65d0
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 28 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

* Add a log level setting ([#117](https://github.com/evanw/esbuild/issues/117))

You can now silence esbuild except for errors with `--log-level=error`, or except for errors and warnings with `--log-level=warning`.

## 0.4.0

* Add the `esm` output format ([#48](https://github.com/evanw/esbuild/issues/48))
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ Advanced options:
--sourcemap=external Do not link to the source map with a comment
--sourcefile=... Set the source file for the source map (for stdin)
--error-limit=... Maximum error count or 0 to disable (default 10)
--log-level=... Disable logging (info, warning, error)

--trace=... Write a CPU trace to this file
--cpuprofile=... Write a CPU profile to this file
Expand Down
53 changes: 35 additions & 18 deletions cmd/esbuild/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Advanced options:
--sourcemap=external Do not link to the source map with a comment
--sourcefile=... Set the source file for the source map (for stdin)
--error-limit=... Maximum error count or 0 to disable (default 10)
--log-level=... Disable logging (info, warning, error)
--trace=... Write a CPU trace to this file
--cpuprofile=... Write a CPU profile to this file
Expand Down Expand Up @@ -84,6 +85,12 @@ type argsObject struct {
entryPaths []string
}

func (args argsObject) logInfo(text string) {
if args.logOptions.LogLevel <= logging.LevelInfo {
fmt.Fprintf(os.Stderr, "%s\n", text)
}
}

func exitWithError(text string) {
colorRed := ""
colorBold := ""
Expand Down Expand Up @@ -377,6 +384,18 @@ func parseArgs(fs fs.FS, rawArgs []string) (argsObject, error) {
return argsObject{}, fmt.Errorf("Invalid JSX fragment: %s", arg)
}

case strings.HasPrefix(arg, "--log-level="):
switch arg[len("--log-level="):] {
case "info":
args.logOptions.LogLevel = logging.LevelInfo
case "warning":
args.logOptions.LogLevel = logging.LevelWarning
case "error":
args.logOptions.LogLevel = logging.LevelError
default:
return argsObject{}, fmt.Errorf("Invalid log level: %s", arg)
}

case strings.HasPrefix(arg, "--trace="):
args.traceFile = arg[len("--trace="):]

Expand Down Expand Up @@ -438,9 +457,6 @@ func parseArgs(fs fs.FS, rawArgs []string) (argsObject, error) {
// Write to stdout by default if there's only one input file
if len(args.entryPaths) == 1 && args.bundleOptions.AbsOutputFile == "" && args.bundleOptions.AbsOutputDir == "" {
args.bundleOptions.WriteToStdout = true
if args.bundleOptions.SourceMap != bundler.SourceMapNone {
args.bundleOptions.SourceMap = bundler.SourceMapInline
}
}
} else if !logging.GetTerminalInfo(os.Stdin).IsTTY {
// If called with no input files and we're not a TTY, read from stdin instead
Expand All @@ -457,9 +473,16 @@ func parseArgs(fs fs.FS, rawArgs []string) (argsObject, error) {
return argsObject{}, fmt.Errorf("Cannot use --outdir when reading from stdin")
}
args.bundleOptions.WriteToStdout = true
if args.bundleOptions.SourceMap != bundler.SourceMapNone {
args.bundleOptions.SourceMap = bundler.SourceMapInline
}
}
}

// Change the default value for some settings if we're writing to stdout
if args.bundleOptions.WriteToStdout {
if args.bundleOptions.SourceMap != bundler.SourceMapNone {
args.bundleOptions.SourceMap = bundler.SourceMapInline
}
if args.logOptions.LogLevel == logging.LevelNone {
args.logOptions.LogLevel = logging.LevelWarning
}
}

Expand Down Expand Up @@ -520,7 +543,7 @@ func main() {
}
defer func() {
f.Close()
fmt.Fprintf(os.Stderr, "Wrote to %s\n", args.traceFile)
args.logInfo(fmt.Sprintf("Wrote to %s", args.traceFile))
}()
trace.Start(f)
defer trace.Stop()
Expand All @@ -537,7 +560,7 @@ func main() {
}
defer func() {
f.Close()
fmt.Fprintf(os.Stderr, "Wrote to %s\n", args.cpuprofileFile)
args.logInfo(fmt.Sprintf("Wrote to %s", args.cpuprofileFile))
}()
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
Expand All @@ -548,7 +571,7 @@ func main() {
// return useful information for esbuild, since it's so fast. Let's keep
// running for 30 seconds straight, which should give us 3,000 samples.
seconds := 30.0
fmt.Fprintf(os.Stderr, "Running for %g seconds straight due to --cpuprofile...\n", seconds)
args.logInfo(fmt.Sprintf("Running for %g seconds straight due to --cpuprofile...", seconds))
for time.Since(start).Seconds() < seconds {
run(fs, args)
}
Expand All @@ -563,9 +586,7 @@ func main() {
}
}()

if !args.bundleOptions.WriteToStdout {
fmt.Fprintf(os.Stderr, "Done in %dms\n", time.Since(start).Nanoseconds()/1000000)
}
args.logInfo(fmt.Sprintf("Done in %dms", time.Since(start).Nanoseconds()/1000000))
}

func run(fs fs.FS, args argsObject) {
Expand Down Expand Up @@ -612,9 +633,7 @@ func run(fs fs.FS, args argsObject) {
if err != nil {
exitWithError(fmt.Sprintf("Failed to write to %s (%s)", path, err.Error()))
}
if !args.bundleOptions.WriteToStdout {
fmt.Fprintf(os.Stderr, "Wrote to %s (%s)\n", path, toSize(len(item.JsContents)))
}
args.logInfo(fmt.Sprintf("Wrote to %s (%s)", path, toSize(len(item.JsContents))))

// Also write the source map
if item.SourceMapAbsPath != "" {
Expand All @@ -623,9 +642,7 @@ func run(fs fs.FS, args argsObject) {
if err != nil {
exitWithError(fmt.Sprintf("Failed to write to %s: (%s)", path, err.Error()))
}
if !args.bundleOptions.WriteToStdout {
fmt.Fprintf(os.Stderr, "Wrote to %s (%s)\n", path, toSize(len(item.SourceMapContents)))
}
args.logInfo(fmt.Sprintf("Wrote to %s (%s)", path, toSize(len(item.SourceMapContents))))
}
}
}
Expand Down
33 changes: 23 additions & 10 deletions internal/logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,16 @@ type Log struct {
msgs chan Msg
}

type MsgKind int
type LogLevel int8

const (
LevelNone LogLevel = iota
LevelInfo
LevelWarning
LevelError
)

type MsgKind uint8

const (
Error MsgKind = iota
Expand Down Expand Up @@ -66,10 +75,6 @@ func (s *Source) RangeOfString(loc ast.Loc) ast.Range {
return ast.Range{loc, 0}
}

func NewLog(msgs chan Msg) Log {
return Log{msgs}
}

type MsgCounts struct {
Errors int
Warnings int
Expand Down Expand Up @@ -109,7 +114,7 @@ type TerminalInfo struct {
func NewStderrLog(options StderrOptions) (Log, func() MsgCounts) {
msgs := make(chan Msg)
done := make(chan MsgCounts)
log := NewLog(msgs)
log := Log{msgs}
terminalInfo := GetTerminalInfo(os.Stderr)

switch options.Color {
Expand All @@ -122,15 +127,22 @@ func NewStderrLog(options StderrOptions) (Log, func() MsgCounts) {
go func(msgs chan Msg, done chan MsgCounts) {
counts := MsgCounts{}
for msg := range msgs {
os.Stderr.WriteString(msg.String(options, terminalInfo))
switch msg.Kind {
case Error:
counts.Errors++
if options.LogLevel <= LevelError {
os.Stderr.WriteString(msg.String(options, terminalInfo))
}
case Warning:
counts.Warnings++
if options.LogLevel <= LevelWarning {
os.Stderr.WriteString(msg.String(options, terminalInfo))
}
}
if options.ExitWhenLimitIsHit && options.ErrorLimit != 0 && counts.Errors >= options.ErrorLimit {
fmt.Fprintf(os.Stderr, "%s reached (disable error limit with --error-limit=0)\n", counts.String())
if options.LogLevel <= LevelInfo {
fmt.Fprintf(os.Stderr, "%s reached (disable error limit with --error-limit=0)\n", counts.String())
}
os.Exit(1)
}
}
Expand All @@ -140,7 +152,7 @@ func NewStderrLog(options StderrOptions) (Log, func() MsgCounts) {
return log, func() MsgCounts {
close(log.msgs)
counts := <-done
if counts.Warnings != 0 || counts.Errors != 0 {
if options.LogLevel <= LevelInfo && (counts.Warnings != 0 || counts.Errors != 0) {
fmt.Fprintf(os.Stderr, "%s\n", counts.String())
}
return counts
Expand All @@ -150,7 +162,7 @@ func NewStderrLog(options StderrOptions) (Log, func() MsgCounts) {
func NewDeferLog() (Log, func() []Msg) {
msgs := make(chan Msg)
done := make(chan []Msg)
log := NewLog(msgs)
log := Log{msgs}

go func(msgs chan Msg, done chan []Msg) {
result := []Msg{}
Expand Down Expand Up @@ -186,6 +198,7 @@ type StderrOptions struct {
ErrorLimit int
ExitWhenLimitIsHit bool
Color StderrColor
LogLevel LogLevel
}

func (msg Msg) String(options StderrOptions, terminalInfo TerminalInfo) string {
Expand Down
2 changes: 2 additions & 0 deletions npm/esbuild/lib/main.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export declare type Target = 'esnext' | 'es6' | 'es2015' | 'es2016' | 'es2017' |
export declare type Platform = 'browser' | 'node';
export declare type Format = 'iife' | 'cjs' | 'esm';
export declare type Loader = 'js' | 'jsx' | 'ts' | 'tsx' | 'json' | 'text' | 'base64' | 'dataurl';
export declare type LogLevel = 'info' | 'warning' | 'error';

interface CommonOptions {
sourcemap?: boolean | 'inline' | 'external';
Expand Down Expand Up @@ -29,6 +30,7 @@ export interface BuildOptions extends CommonOptions {
color?: boolean;
external?: string[];
loader?: { [ext: string]: Loader };
logLevel?: LogLevel;

entryPoints: string[];

Expand Down
1 change: 1 addition & 0 deletions npm/esbuild/lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ exports.build = options => {
if (options.platform) flags.push(`--platform=${options.platform}`);
if (options.format) flags.push(`--format=${options.format}`);
if (options.color) flags.push(`--color=${options.color}`);
if (options.logLevel) flags.push(`--log-level=${options.logLevel}`);
if (options.external) for (const name of options.external) flags.push(`--external:${name}`);
if (options.loader) for (const ext in options.loader) flags.push(`--loader:${ext}=${options.loader[ext]}`);

Expand Down

0 comments on commit 6dc65d0

Please sign in to comment.