Skip to content

Commit

Permalink
fix(jsii): color codes are logged to logfiles (#3284)
Browse files Browse the repository at this point in the history
When the output is not a terminal, color codes get in the way. They
lead to unreadable logging like this:

```
monocdk: ^[[96mlib/aws-apigateway/lib/domain-name.ts^[[0m:^[[93m114^[[0m:^[[93m19^[[0m - ^[[93mwarning^[[0m^[[90m JSII5019: ^[[0mThe property name "domainName" conflicts with the declaring class "DomainName". This will result in renaming the class to "_DomainName" in C#. Consider renaming "domainName".
monocdk: �[7m114�[0m   public readonly domainName: string;
monocdk: �[7m   �[0m �[93m                  ~~~~~~~~~~�[0m
```

Don't output color codes if we detect the output is not a TTY.



---

By submitting this pull request, I confirm that my contribution is made under the terms of the [Apache 2.0 license].

[Apache 2.0 license]: https://www.apache.org/licenses/LICENSE-2.0
  • Loading branch information
rix0rrr authored Dec 23, 2021
1 parent d0b2810 commit 2c8c647
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions packages/jsii/bin/jsii.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import '@jsii/check-node/run';

import * as log4js from 'log4js';
import * as path from 'path';
import * as util from 'util';
import * as yargs from 'yargs';

import { Compiler } from '../lib/compiler';
Expand Down Expand Up @@ -132,15 +133,26 @@ const warningTypes = Object.keys(enabledWarnings);
});

function _configureLog4js(verbosity: number) {
const stderrColor = !!process.stderr.isTTY;
const stdoutColor = !!process.stdout.isTTY;

log4js.addLayout('passThroughNoColor', () => {
return (loggingEvent) => stripAnsi(util.format(...loggingEvent.data));
});

log4js.configure({
appenders: {
console: {
type: 'stderr',
layout: { type: 'colored' },
layout: { type: stderrColor ? 'colored' : 'basic' },
},
[utils.DIAGNOSTICS]: {
type: 'stdout',
layout: { type: 'messagePassThrough' },
layout: {
type: stdoutColor
? 'messagePassThrough'
: ('passThroughNoColor' as any),
},
},
},
categories: {
Expand Down Expand Up @@ -168,3 +180,11 @@ function _configureLog4js(verbosity: number) {
}
}
}

const ANSI_REGEX =
// eslint-disable-next-line no-control-regex
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;

function stripAnsi(x: string): string {
return x.replace(ANSI_REGEX, '');
}

0 comments on commit 2c8c647

Please sign in to comment.