@zwa73/utils 1.0.202 → 1.0.204

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/UtilLogger.ts DELETED
@@ -1,390 +0,0 @@
1
- import path from 'pathe';
2
- import * as winston from 'winston';
3
- import DailyRotateFile from 'winston-daily-rotate-file';
4
- import {inspect} from 'util';
5
-
6
-
7
-
8
- /**hrtime所产生的的记录 */
9
- export type HRTimeLog = {
10
- /**秒数 */
11
- 0:number;
12
- /**纳秒数 */
13
- 1:number;
14
- };
15
-
16
- /**log等级 undefined相当于 silly */
17
- export type LogLevel = "fatal"|"error"|"warn"|"info"|"http"|"verbose"|"debug"|"silly"|undefined;
18
- const logLevels = {
19
- fatal: 0,
20
- error: 1,
21
- warn: 2,
22
- info: 3,
23
- http: 4,
24
- verbose: 5,
25
- debug: 6,
26
- silly: 7
27
- };
28
- const colorizer = winston.format.colorize();
29
- colorizer.addColors({
30
- fatal: 'bold yellow redBG',
31
- error: 'bold yellow',
32
- warn: 'yellow',
33
- info: 'white',
34
- debug: 'bold cyan',
35
- silly: 'bold magenta'
36
- });
37
-
38
-
39
- export class SLogger{
40
- /**获取一个Logger,如不存在则用默认参数创建
41
- * @param name - logger的名称 默认default
42
- * @returns 获取的logger
43
- */
44
- static getLogger(name:string="default"):SLogger{
45
- let out = SLogger.loggerTable[name];
46
- if(out==null){
47
- SLogger.createLogger(name);
48
- out = SLogger.loggerTable[name];
49
- }
50
- return out;
51
- }
52
- /**创建Logger
53
- * @param name - logger的名称 默认default
54
- * @param consoleLevel - 输出到控制台的最低等级 默认info
55
- * @param outFloder - log的输出文件夹路径 如./log/
56
- * @param fileLevel - 输出到文件的最低等级 默认info
57
- * @returns 创建完成的logger
58
- */
59
- static createLogger(name:string="default",consoleLevel:LogLevel="info",outFloder?:string,fileLevel:LogLevel="info"):SLogger{
60
- const transports:winston.transport[]=[];
61
- if(outFloder!=null){
62
- const fileFormat = winston.format.combine(
63
- winston.format.timestamp({ format: 'HH:mm:ss' }),
64
- winston.format.printf((info) => {
65
- const level = info.level.toUpperCase();
66
- const message = info.message as string;
67
- //格式化
68
- //let format = `[${info.timestamp}] [${level}]: `
69
- //let space = " ".repeat(format.length);
70
- let messageList = message.split("\n");
71
- return `[${info.timestamp}] [${level.toUpperCase()}]: ${messageList.join("\n")}`
72
- }),
73
- );
74
- transports.push(new DailyRotateFile({
75
- filename: path.join(outFloder,'log-%DATE%.txt'),
76
- datePattern: 'YYYY-MM-DD',
77
- level:fileLevel,
78
- format:fileFormat,
79
- }));
80
- }
81
- const consoleFormat = winston.format.combine(
82
- winston.format.timestamp({ format: 'HH:mm:ss' }),
83
- winston.format.printf((info) => {
84
- const level = info.level.toUpperCase();
85
- const message = info.message as string;
86
- const colorizedLevel = colorizer.colorize(info.level, level);
87
- //格式化
88
- //let format = `[${info.timestamp}] [${level}]: `
89
- //let space = " ".repeat(format.length);
90
- let messageList = message.split("\n");
91
- messageList[0]=colorizer.colorize(info.level, messageList[0])
92
- for(let i=1;i<messageList.length;i++)
93
- messageList[i]=colorizer.colorize(info.level, messageList[i]);
94
- let formattedMessage = messageList.join("\n");
95
- const prefix = `[${info.timestamp}] [${colorizedLevel}]: `;
96
- if (formattedMessage.startsWith(prefix))
97
- formattedMessage = formattedMessage.slice(prefix.length);
98
- return `${prefix}${formattedMessage}`;
99
- //return `[${info.timestamp}] [${colorizedLevel}]: ${messageList.join("\n")}`;
100
- }),
101
- );
102
- transports.push(new winston.transports.Console({
103
- level: consoleLevel,
104
- format:consoleFormat,
105
- }));
106
- const logger = winston.createLogger({
107
- levels:logLevels,
108
- transports: transports,
109
- });
110
-
111
- const out = new SLogger();
112
- out._logger = logger;
113
-
114
- if(SLogger.loggerTable[name]!=null){
115
- let old = SLogger.loggerTable[name];
116
- old._logger.transports.forEach(tp=>{
117
- if(tp.close!=null) tp.close();
118
- })
119
- }
120
-
121
- SLogger.loggerTable[name] = out;
122
- return out;
123
- }
124
- private constructor(){}
125
- private _logger:winston.Logger = null as any as winston.Logger;
126
- /**记录Logger的表 */
127
- private static readonly loggerTable:Record<string,SLogger> = {};
128
- /**记录Logger的表 */
129
- private static readonly timeTable:Record<string,HRTimeLog> = {};
130
-
131
-
132
-
133
- //———————————————————— function ——————————————————————//
134
- /**产生一条对应等级的log 返回自身
135
- * @param level - log等级
136
- * @param messages - log消息
137
- * @returns 自身
138
- */
139
- log(level:LogLevel,...messages:Array<any>):SLogger{
140
- level ??= "silly";
141
- const strMessages:Array<string> = [];
142
- //上一条是字符串字符串
143
- let preIsString = true;
144
- for(let message of messages){
145
- let out:string;
146
- //非string类型
147
- if(typeof message!=="string"){
148
- out=`<${typeof message}> ${inspect(message)}`;
149
- preIsString=false;
150
- }else if(!preIsString){
151
- //如果上一条不是字符串则需要添加<string>类型标记
152
- out = `<${typeof message}> ${inspect(message)}`;
153
- preIsString=true;
154
- }else{
155
- out = message;
156
- }
157
- strMessages.push(out);
158
- }
159
- const outMessage = strMessages.join("\n");
160
- this._logger.log(level,outMessage);
161
- return this;
162
- }
163
- /**产生一条fatal等级的log 返回自身
164
- * @param messages - log消息
165
- * @returns 自身
166
- */
167
- fatal(...messages:Array<any>):SLogger {
168
- return this.log("fatal",...messages);;
169
- }
170
- /**产生一条error等级的log 返回自身
171
- * @param messages - log消息
172
- * @returns 自身
173
- */
174
- error(...messages:Array<any>):SLogger {
175
- return this.log("error",...messages);;
176
- }
177
- /**产生一条warn等级的log 返回自身
178
- * @param messages - log消息
179
- * @returns 自身
180
- */
181
- warn(...messages:Array<any>):SLogger {
182
- return this.log("warn",...messages);;
183
- }
184
- /**产生一条info等级的log 返回自身
185
- * @param messages - log消息
186
- * @returns 自身
187
- */
188
- info(...messages:Array<any>):SLogger {
189
- return this.log("info",...messages);
190
- }
191
- /**产生一条http等级的log 返回自身
192
- * @param messages - log消息
193
- * @returns 自身
194
- */
195
- http(...messages:Array<any>):SLogger {
196
- return this.log("http",...messages);
197
- }
198
- /**产生一条verbose等级的log 返回自身
199
- * @param messages - log消息
200
- * @returns 自身
201
- */
202
- verbose(...messages:Array<any>):SLogger {
203
- return this.log("verbose",...messages);
204
- }
205
- /**产生一条debug等级的log 返回自身
206
- * @param messages - log消息
207
- * @returns 自身
208
- */
209
- debug(...messages:Array<any>):SLogger {
210
- return this.log("debug",...messages);
211
- }
212
- /**产生一条silly等级的log 返回自身
213
- * @param messages - log消息
214
- * @returns 自身
215
- */
216
- silly(...messages:Array<any>):SLogger {
217
- return this.log("silly",...messages);
218
- }
219
- /**记录当前时间戳并存入表
220
- * @param flag - 记录的命名
221
- * @returns 记录的时间
222
- */
223
- time(flag:string):HRTimeLog{
224
- let hrtime = process.hrtime();
225
- SLogger.timeTable[flag]=hrtime;
226
- return hrtime;
227
- }
228
- /**根据之前记录的时间戳计算经过的时间 并输出log
229
- * @param flag - 记录的命名
230
- * @param level - log等级 === null时不产生log
231
- * @returns 格式化的时间字符串
232
- */
233
- timeEnd(flag:string,level:LogLevel|null="info"):string|undefined{
234
- const start = SLogger.timeTable[flag];
235
- if(start==null){
236
- this.warn("SLogger.timeEnd 错误 flag:"+flag+" 不存在");
237
- return;
238
- }
239
- const timelen = process.hrtime(start as any as [number,number]);
240
-
241
- const totalMicroseconds = (timelen[0] * 1e9 + timelen[1]) / 1000;
242
- const microseconds = totalMicroseconds % 1000;
243
- const totalMilliseconds = totalMicroseconds / 1000;
244
- const milliseconds = Math.floor(totalMilliseconds % 1000);
245
- const totalSeconds = totalMilliseconds / 1000;
246
- const seconds = Math.floor(totalSeconds % 60);
247
- const totalMinutes = totalSeconds / 60;
248
- const minutes = Math.floor(totalMinutes % 60);
249
- const totalHours = totalMinutes / 60;
250
- const hours = Math.floor(totalHours % 24);
251
- const totalDay = totalHours / 24;
252
- const Days = Math.floor(totalDay);
253
-
254
- let out = '';
255
- if(totalSeconds>60){
256
- let result = '';
257
- let format = '';
258
- let acc = 0;
259
- const maxAcc = 3;
260
-
261
- const concat = (num:number,sep:string,
262
- formatText:string,resultText:string): void => {
263
- const hasResult = result.length>0;
264
- const need = (hasResult || num>0) && (acc < maxAcc);
265
- if(!need) return;
266
- if(result.length>0) result+=sep;
267
- if(format.length>0) format+=sep;
268
- result += resultText;
269
- format += formatText;
270
- acc++;
271
- }
272
- concat(Days,':','dd',
273
- `${Days.toString()}`);
274
- concat(hours,':','HH',
275
- `${hours.toString().padStart(2, '0')}`);
276
- concat(minutes,':','mm',
277
- `${minutes.toString().padStart(2, '0')}`);
278
- concat(seconds,':','ss',
279
- `${seconds.toString().padStart(2, '0')}`);
280
- concat(milliseconds,'.','mmm',
281
- `${milliseconds.toString().padStart(3, '0')}`);
282
- //result = result.replace(/^(0(?![^0-9]))+/, '');
283
- result = result.replace(/^0+([0-9])/,"$1");
284
- out = `${result} (${format})`;
285
- }else if(totalMilliseconds>1000){
286
- out = `${totalSeconds.toFixed(3)}s`
287
- }else{
288
- out = `${totalMilliseconds.toFixed(3)}ms`
289
- }
290
-
291
- if(level!==null)
292
- this.log(level,`${flag}: ${out}`);
293
- delete SLogger.timeTable[flag];
294
- return out;
295
- }
296
-
297
-
298
-
299
- //———————————————————— static ——————————————————————//
300
- /**名称为default的slogger实例 */
301
- private static get defaultInstance():SLogger{
302
- if(SLogger.loggerTable.default==null)
303
- SLogger.createLogger();
304
- return SLogger.loggerTable.default;
305
- }
306
- /**让名称为default的logger 产生一条对应等级的log 返回自身
307
- * @param level - log等级
308
- * @param messages - log消息
309
- * @returns 自身
310
- */
311
- static log(level: LogLevel, ...messages:Array<any>):SLogger{
312
- level = level??"silly";
313
- this.defaultInstance.log(level,...messages);
314
- return this.defaultInstance;
315
- }
316
- /**让名称为default的logger 产生一条fatal等级的log 返回自身
317
- * @param messages - log消息
318
- * @returns 自身
319
- */
320
- static fatal(...messages:Array<any>):SLogger {
321
- return this.log("fatal",...messages);;
322
- }
323
- /**让名称为default的logger 产生一条error等级的log 返回自身
324
- * @param messages - log消息
325
- * @returns 自身
326
- */
327
- static error(...messages:Array<any>):SLogger {
328
- return this.log("error",...messages);;
329
- }
330
- /**让名称为default的logger 产生一条warn等级的log 返回自身
331
- * @param messages - log消息
332
- * @returns 自身
333
- */
334
- static warn(...messages:Array<any>):SLogger {
335
- return this.log("warn",...messages);;
336
- }
337
- /**让名称为default的logger 产生一条info等级的log 返回自身
338
- * @param messages - log消息
339
- * @returns 自身
340
- */
341
- static info(...messages:Array<any>):SLogger {
342
- return this.log("info",...messages);
343
- }
344
- /**让名称为default的logger 产生一条http等级的log 返回自身
345
- * @param messages - log消息
346
- * @returns 自身
347
- */
348
- static http(...messages:Array<any>):SLogger {
349
- return this.log("http",...messages);
350
- }
351
- /**让名称为default的logger 产生一条verbose等级的log 返回自身
352
- * @param messages - log消息
353
- * @returns 自身
354
- */
355
- static verbose(...messages:Array<any>):SLogger {
356
- return this.log("verbose",...messages);
357
- }
358
- /**让名称为default的logger 产生一条debug等级的log 返回自身
359
- * @param messages - log消息
360
- * @returns 自身
361
- */
362
- static debug(...messages:Array<any>):SLogger {
363
- return this.log("debug",...messages);
364
- }
365
- /**让名称为default的logger 产生一条silly等级的log 返回自身
366
- * @param messages - log消息
367
- * @returns 自身
368
- */
369
- static silly(...messages:Array<any>):SLogger {
370
- return this.log("silly",...messages);
371
- }
372
- /**让名称为default的logger 记录当前时间戳并存入表
373
- * @param flag - 记录的命名
374
- * @returns 记录的时间
375
- */
376
- static time(flag:string):HRTimeLog{
377
- return this.defaultInstance.time(flag);
378
- }
379
- /**让名称为default的logger 根据之前记录的时间戳计算经过的时间 并输出log
380
- * @param flag - 记录的命名
381
- * @param level - log等级
382
- * @returns
383
- */
384
- static timeEnd(flag:string,level:LogLevel="info"):void{
385
- this.defaultInstance.timeEnd(flag,level);
386
- }
387
- }
388
-
389
-
390
-
package/src/UtilSymbol.ts DELETED
@@ -1,45 +0,0 @@
1
- import { Outcome } from "./UtilInterfaces";
2
-
3
-
4
- /**成功 经过验证的结果 */
5
- export const Success = Symbol("Success");
6
- export type Success = typeof Success;
7
- /**失败 可重试的 */
8
- export const Failed = Symbol("Failed");
9
- export type Failed = typeof Failed;
10
- /**不存在 无 */
11
- export const None = Symbol("None");
12
- export type None = typeof None;
13
- /**未初始化的 用于静态构造函数标记*/
14
- export const Uninited = Symbol("Uninited");
15
- export type Uninited = typeof Uninited;
16
- /**完成 未经验证/未超时的结果
17
- * Success扩展
18
- * 仅在Success同时出现时使用
19
- */
20
- export const Completed = Symbol("Completed");
21
- export type Completed = typeof Completed;
22
- /**终止 熔断运行
23
- * Failed扩展
24
- * 仅在Failed同时出现时使用
25
- */
26
- export const Terminated = Symbol("Terminated");
27
- export type Terminated = typeof Terminated;
28
- /**超时 超时类型的失败
29
- * Failed扩展
30
- * 仅在超时时使用
31
- */
32
- export const Timeout = Symbol("Timeout");
33
- export type Timeout = typeof Timeout;
34
- /**失败及其拓展 */
35
- export type FailedLike = Failed|Timeout|Terminated;
36
- /**成功及其拓展 */
37
- export type SuccessLike = Success|Completed;
38
- /**任意状态标识符 */
39
- export type StatusSymbol = FailedLike|SuccessLike|None|Uninited;
40
- /**结果为 None 的 Outcome */
41
- export type NoneOut = Outcome<None,None>;
42
- export const NoneOut = {
43
- status:None,
44
- result:None,
45
- } as const as NoneOut;
package/src/backup.txt DELETED
@@ -1,102 +0,0 @@
1
- import { ComposedClass, FuncPropNames } from "./UtilInterfaces";
2
-
3
- /**类组合
4
- * 将mixinList每个成员的字段混入base
5
- * @param base - 基础类
6
- * @param mixinList - 目标类
7
- * @returns - 混合完成的类
8
- */
9
- export function composeClassFull<Base extends object,MixinList extends object[]>
10
- (base:Base,...mixinList:MixinList):ComposedFullClassMult<Base,MixinList>{
11
- let obj = base as any;
12
- for(let mixin of mixinList as any){
13
- let propks = Object.getOwnPropertyNames(mixin.constructor.prototype)
14
- for(const key of propks){
15
- if(key != "constructor"){
16
- Object.defineProperty(obj, key, {
17
- get: ()=>mixin[key],
18
- set: (value)=>{mixin[key] = value},
19
- enumerable:true,
20
- //writable: true,
21
- configurable: true
22
- });
23
- //obj[key] = (mixin as any)[key];
24
- }
25
- }
26
- for(const key in mixin){
27
- Object.defineProperty(obj, key, {
28
- get: ()=>mixin[key],
29
- set: (value)=>{mixin[key] = value},
30
- enumerable:true ,
31
- //writable: true ,
32
- configurable: true
33
- });
34
- //obj[key] = (mixin as any)[key];
35
- }
36
- }
37
- return obj;
38
- }
39
-
40
- ///**组合的类 嵌套变体 */
41
- //export type ComposedClassMult<Base extends object,
42
- // Mixin1 extends object = {}, PropKeys1 extends keyof Mixin1 = keyof Mixin1,
43
- // Mixin2 extends object = {}, PropKeys2 extends keyof Mixin2 = keyof Mixin2,
44
- // Mixin3 extends object = {}, PropKeys3 extends keyof Mixin3 = keyof Mixin3,
45
- // Mixin4 extends object = {}, PropKeys4 extends keyof Mixin4 = keyof Mixin4,
46
- // Mixin5 extends object = {}, PropKeys5 extends keyof Mixin5 = keyof Mixin5,
47
- // Mixin6 extends object = {}, PropKeys6 extends keyof Mixin6 = keyof Mixin6> =
48
- // ComposedClass<ComposedClass<ComposedClass<
49
- // ComposedClass<ComposedClass<ComposedClass<
50
- // Base,
51
- // Mixin1,PropKeys1>,Mixin2,PropKeys2>,Mixin3,PropKeys3>,
52
- // Mixin4,PropKeys4>,Mixin5,PropKeys5>,Mixin6,PropKeys6>
53
- //
54
- ///**递归多组合 仅单key有效 */
55
- //type ComposedClassOnceKey<Base extends object,Data extends [object,string][]> =
56
- // Data extends [[infer Mixin extends object, infer FuncKeys], ...infer Rest]
57
- // ? FuncKeys extends FuncPropNames<Mixin>
58
- // ? Rest extends [any, any][]
59
- // ? ComposedClassOnceKey<ComposedClass<Base, Mixin, FuncKeys>,Rest>
60
- // : Base
61
- // : Base
62
- // : Base;
63
-
64
-
65
-
66
- /**组合的类
67
- * @template Base - 基类
68
- * @template Mixin - 待混入的类
69
- */
70
- export type ComposedFullClass<Base extends object,Mixin extends object> = Base&Mixin;
71
- /**组合的类 多组合变体
72
- * @template Base - 基类
73
- * @template MixinList- 待混入的类型数组
74
- */
75
- export type ComposedFullClassMult<Base extends object,MixinList extends object[]> =
76
- MixinList extends [infer Mixin, ...infer Rest]
77
- ? Mixin extends object
78
- ? Rest extends object[]
79
- ? ComposedFullClassMult<ComposedFullClass<Base,Mixin>,Rest>
80
- : Base
81
- : Base
82
- : Base;
83
-
84
- /**将一个类型的所有方法的 `this` 参数改为 `T` 类型
85
- * @template Methods - 待更改的函数表
86
- * @template T - 目标this类型
87
- */
88
- export type MethodsThisAs<Methods, T> = {
89
- [K in keyof Methods]:
90
- Methods[K] extends (...args: infer A) => infer R
91
- ? (this: T, ...args: A) => R
92
- : Methods[K];
93
- };
94
-
95
- /**尝试断言一个类的原型
96
- * 其所有函数的 this 都必须为某个类型
97
- * assignThisAs<Self,T>(Self.prototype);
98
- * @template Self - 类的类型
99
- * @template T - 目标this类型
100
- * @param prototype - 类的原型
101
- */
102
- export function assertThisAs<Self,T>(prototype: MethodsThisAs<Self, T>) {}
package/src/index.ts DELETED
@@ -1,13 +0,0 @@
1
- export * from './UtilFunctions';
2
- export * from './UtilInterfaces';
3
- export * from './UtilSymbol';
4
- export * from './UtilClass';
5
- export * from './UtilCom';
6
- export * from './UtilCodecs';
7
- export * from './UtilFfmpegTools';
8
- export * from './UtilDecorators';
9
- export * from './UtilFileTools';
10
- export * from './UtilLogger';
11
- export * from './UtilFP';
12
- export * from './QuickExport';
13
- export * from './UtilI18n';
package/test.bat DELETED
@@ -1,2 +0,0 @@
1
- call npm run test
2
- pause
package/watch.bat DELETED
@@ -1 +0,0 @@
1
- npm run watch