我有一个logger对象,用于格式化带有时间戳记,发件人的日志消息,并将行的格式设置为最长80个字符。
var paddedSender = message.Sender.padStart( 6 );
var string = `=-[ ${message.Timestamp} ][ ${paddedSender} ] `;
var remainingLength = this.CONSOLE_MAX_LENGTH - string.length - 3;
var lines = [];
var numLines = Math.ceil( message.Body.length / remainingLength );
for ( var i = 0, o = 0; i < numLines; i++ , o += remainingLength )
lines.push( message.Body.substr( o, remainingLength ) );
string += lines.shift().padEnd( remainingLength ) + ' -=';
while ( lines.length > 0 )
string += '\n'
+ '=-'
+ '-'.repeat( message.Timestamp.length + 4 )
+ '-'.repeat( paddedSender.length + 4 )
+ ` ${lines.shift().padEnd( remainingLength )} `
+ '-=';
return string;
这将产生类似于以下内容的输出:
================================================================================
=-[ 06/08 11:30:36 ][ SYSTEM ] Initializing... -=
=-[ 06/08 11:30:36 ][ SYSTEM ] Logger Initialized -=
=-[ 06/08 11:30:37 ][ SYSTEM ] WebService Initialized -=
=-[ 06/08 11:30:38 ][ WEBCLI ] API Returned 400 Bad Request(Endpoint: undefin -=
=----------------------------- ed) (Err: Invalid id) -=
到目前为止,它的作用符合预期。但是,我想通过在空格之间开始新行而不是在达到字符限制时进行换行。
例如,我想要此消息:
=-[ 06/08 11:30:38 ][ WEBCLI ] API Returned 400 Bad Request(Endpoint: undefin -=
=----------------------------- ed) (Err: Invalid id) -=
要这样格式化:
=-[ 06/08 11:30:38 ][ WEBCLI ] API Returned 400 Bad Request(Endpoint: -=
=----------------------------- undefined) (Err: Invalid id) -=
我该如何实现?
答案 0 :(得分:1)
您可以获取文本并获取想要的size
,然后检查零件字符串末尾的位置是否为空格,然后将其拆分并通过调整长度将其推入数组。
var string = 'API Returned 400 Bad Request(Endpoint: undefined) (Err: Invalid id) Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',
size = 46,
parts = [],
start = 0,
end;
while (start <= string.length) {
end = start + size;
if (end < string.length) while (string[end] !== ' ') --end;
parts.push(string.slice(start, end).padEnd(size, ' '));
start = end + 1;
}
console.log(parts);
.as-console-wrapper { max-height: 100% !important; top: 0; }