Last active
May 6, 2025 19:47
-
-
Save kadamwhite/0dcc48668fca6db59d295a49a2627ae4 to your computer and use it in GitHub Desktop.
reformat-wp-env-log-output: pipe docker output from `docker logs -f <container>` through this to clean up and simplify the output. Useful for WP-Env or VIP Dev-Env. Can filter out lines with `--suppress=string1,string2`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
// Run with `<command> 2>&1 | this-script` to capture and format log output. | |
const ipLogPattern = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} .*(POST|PUT|GET|HEAD|DELETE|OPTIONS)/ | |
const logContextPattern = /^\[[^\]]+\] \[[a-z_]+:[a-z_]+\] \[pid[^\]]+\] (\[client [0-9][^\]]+\])?/; | |
const suppressionListFlag = /^--suppress=/; | |
const suppressionListArg = process.argv.slice( 2 ).find( arg => suppressionListFlag.test( arg ) ); | |
const suppressionList = suppressionListArg | |
? suppressionListArg.replace( suppressionListFlag, '' ).split( ',' ) | |
: []; | |
/** | |
* Handle a stream of stdout or stderr. | |
* | |
* @param {import('fs').ReadStream} stream Input stream to process. | |
* @return {string} Rendered and maybe-filtered string output. | |
*/ | |
function processLine( stream ) { | |
const line = stream.toString().replace( /\\n/, '\n' ); | |
if ( /\n/.test( line ) ) { | |
// Multi-line output. Process individually. | |
return line.split( /\n/ ).map( processLine ).filter( Boolean ).join( '\n' ); | |
} | |
if ( ipLogPattern.test( line ) ) { | |
return ''; | |
} | |
for ( const suppressedPattern of suppressionList ) { | |
if ( line.includes( suppressedPattern ) ) { | |
return ''; | |
} | |
} | |
// Strip off non-helpful-for-local-debugging context information | |
// so that the output is more scannable. | |
return line | |
.replace( logContextPattern, '' ) | |
.replace( /PHP Fatal error:\s+/, '\n\nPHP Fatal error:\n' ); | |
} | |
/** | |
* Monitor, filter, and log the output from a stream. | |
* | |
* Writes to process.stdout. | |
* | |
* @async | |
* @param {NodeJS.ReadStream} readableStream stdin or similar modern Node read stream. | |
*/ | |
async function monitor( readableStream ) { | |
for await ( const chunk of readableStream ) { | |
const line = processLine( chunk ); | |
if ( line ) { | |
process.stdout.write( line ); | |
} | |
} | |
} | |
monitor( process.stdin ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment