1 Star 5 Fork 1

Ericple / log4a

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

Log4a

轻量、易集成、易使用,有时甚至可以不需写代码的HarmonyOS log系统,灵感来自log4j。

Log4a文档

特点

  • 支持TS工程引入
  • 提供日志装饰器,无需自己配置log4a,自动跟踪函数调用情况
  • 使用fatal、error输出时,支持打印调用堆栈
  • 支持日志输出到文件,利用多线程特性,提高日志输出到文件的性能
  • 格式化日志输出,借鉴log4j,贴合使用习惯
  • Logger统一管理,降低内存占用
  • 支持格式化打印对象
  • 通过设置日志级别,提供日志过滤服务
  • 支持日志加密写出到文件
  • 支持配置日志文件最大容量,溢出后新建日志文件
  • 支持配置日志文件备份数量,溢出后滚动删除

由于ohpm中心仓库审核需要时间,若您遇到恶性bug但中心仓库未提供更新,请先移步log4a代码仓库 检查是否存在新版本,若没有,您可以新建issue ,或向我发送邮件,我将尽快修复。

安装

  • 使用 ohpm 以安装 @pie/log4a
ohpm install @pie/log4a

对于其他安装方式, 请参考 这篇文章.

使用

通用流程

  • 获取logger

使用LogManager.getLogger(context)获取当前对象的可用Logger。该方法传入this即可。

import { LogManager, Logger } from '@pie/log4a';

class LogTestClass {
  private logger: Logger = LogManager.getLogger(this);
  // ... Other code
}
  • 使用logger

获取logger后,即可开始打印日志:

import { LogManager, Logger } from '@pie/log4a';

class LogTestClass {
  private logger: Logger = LogManager.getLogger(this);

  add(a: number, b: number) {
    this.logger.info('calculating {} + {}', a, b);
    return a + b;
  }
}

const adder = new LogTestClass;
adder.add(1, 2);

上面这段代码在执行之后,会打印出这样一条日志

[INFO ] 2024-04-19  23:32:54.746  [LogTestClass:1]  calculating 1 + 2

可以看到,log4a打印出的日志中包含了以下信息:

  • 日志级别
  • 日志时间
  • 日志来源
  • 日志内容

日志来源

当logger属于class或struct时:

对于非静态logger,日志来源为class或struct的名称

对于静态logger,日志来源为Function

import { LogManager, Logger } from '@pie/log4a';
class StaticLogger {
  private static logger: Logger = LogManager.getLogger(this);
  static hello() {
    StaticLogger.logger.info("Hello from static logger");
  }
}

这段代码将会打印:

[INFO ] 2024-04-19  23:32:54.746  [Function:1]  Hello from static logger
  • 带标记的日志

对于一些匿名输出,可以通过添加标记的方式便于在日志中进行搜索,例如:

LogManager.anonymous().withMarker(MarkerManager.getMarker("我是一个Marker")).info('这是带Marker的日志');

追踪器

log4a设计了追踪器,它可以帮你跟踪函数运行参数、函数运行结果、模板字符串的构造。

可用的追踪器:

@TraceEntry

  • @TraceEntry:用于跟踪函数运行参数,示例如下:
import { TraceEntry } from '@pie/log4a';

class TestClass {
  @TraceEntry
  add(a: number, b: number): number {
    return a + b;
  }
}

const t = new TestClass;
t.add(1, 2);

虽然没有写任何的log代码,但这段代码在运行后仍然会出现如下log:

[TRACE]	2024-04-20 00:19:43.24	[TestClass:1]	Method: [add] called with arguments [1,2]

这意味着,使用@TraceEntry装饰的函数将会被追踪,每当它被调用时,log4a都会打印一条日志,该日志包含该函数名称及本次调用传入的参数。

@TraceExit

  • @TraceExit:用于跟踪函数运行结果,示例如下:
import { TraceExit } from '@pie/log4a';

class TestClass {
  @TraceExit
  add(a: number, b: number): number {
    return a + b;
  }
}

const t = new TestClass;
t.add(1, 2);

虽然没有写任何的log代码,但这段代码在运行后仍然会出现如下log:

[TRACE]	2024-04-20 00:19:43.24	[TestClass:1]	Method: [add] exited with result: 3

这意味着,使用@TraceExit装饰的函数将会被追踪,每当它被调用时,log4a都会打印一条日志,该日志包含该函数名称及本次调用返回的结果。

TracedStr

  • TracedStr:用于跟踪字符串模板的构建过程,示例如下:
import { TracedStr } from '@pie/log4a';

class TestClass {
  param1: string = 'param1';
  param2: string = 'param2';
  str: string = TracedStr`build with ${this.param1} and ${this.param2}`;
}

const t = new TestClass;

虽然没有写任何的log代码,但这段代码在运行后仍然会出现如下log:

[INFO ]	2024-04-20 00:27:51.989	[Anonymous:1]	built with format: ["build with "," and ",""] and args: ["param1","param2"] (Anonymous)

注意,TracedStr是标签而不是装饰器,因此不需要@前导。

MarkedTracedStr

  • MarkedTracedStr:为了方便使用者追踪特定的模板字符串构建,使用此标签并传入一个字符串作为标记
import { MarkedTracedStr } from '@pie/log4a';

class TestClass {
  param1: string = 'param1';
  param2: string = 'param2';
  str: string = MarkedTracedStr("StrBuilder")`build with ${this.param1} and ${this.param2}`;
}

const t = new TestClass;

虽然没有写任何的log代码,但这段代码在运行后仍然会出现如下log:

[INFO ]	2024-04-20 00:33:31.793	[Anonymous:2]	built with format: ["build with "," and ",""] and args: ["param1","param2"] (StrBuilder)

注意,MarkedTracedStr是函数而不是标签,需要传入一个参数。

Appender

Appender为Logger提供日志输出能力,分为两种类型:FileAppenderConsoleAppender。 新建Logger时,将自动提供一个ConsoleAppender。Appender无法直接被创建,只能通过调用Logger实例下的addFileAppenderaddConsoleAppender来创建并绑定到该Logger.

ConsoleAppender

ConsoleAppender提供向控制台输出日志的能力,每个Logger在创建时,就会带有一个ConsoleAppender,无需手动添加。 一个Logger最多只能拥有一个ConsoleAppender,当您向Logger添加ConsoleAppender时,若已存在,则该appender不会被添加至Logger。

  • 添加一个ConsoleAppender
// this.logger是一个Logger的实例
this.logger.addConsoleAppender(Level.INFO);
  • 移除ConsoleAppender
this.logger.removeTypedAppender(AppenderTypeEnum.CONSOLE);
  • 获取当前Session的历史日志
this.logger.getHistoryOfAppender(AppenderTypeEnum.CONSOLE);

FileAppender

FileAppender提供向文件输出日志的能力。 一个Logger可以有多个FileAppender,如果有多个FileAppender指向同一个文件,则这些FileAppender将会共用一个文件对象。

添加一个FileAppender
this.logger.addFileAppender('/file/log.log', 'mainAppender', Level.INFO);
删除一个FileAppender
this.logger.removeNamedAppender('mainAppender');
获取当前Session的历史日志(从本次开启应用开始)
const history = this.logger.getHistoryOfAppender('mainAppender');
获取所有历史日志(从首次安装并启动应用开始,每次应用销毁后更新,下次继续累计)
const history = this.logger.getAllHistoryOfAppender('mainAppender');
开启多线程支持
this.logger.addFileAppender('/file/log.log', 'mainAppender', Level.INFO, {
  useWorker: true
});
配置最大日志备份文件数量
this.logger.addFileAppender('/file/log.log', 'mainAppender', Level.INFO, {
  maxCacheCount: 10
});
配置最大日志容量
this.logger.addFileAppender('/file/log.log', 'mainAppender', Level.INFO, {
  maxFileSize: 10 // 最大10KB
});

日志级别

为了帮助使用者更容易地从日志中提取有用的信息,log4a引入了日志级别的概念。 Logger和Appender都可以附带日志级别,log4a对Logger的日志等级的处理优先于对appender的日志等级的处理,举例如下:

this.logger.setLevel(Level.ERROR);
this.logger.addFileAppender("/path/to/log.log", "mainFileAppender", Level.INFO);

在这个例子中,由于添加的FileAppender日志级别为INFO,高于Logger的日志级别ERROR,此时WARN级别的日志无法送达Appender。

(日志等级排序为:OFF<FATAL<ERROR<WARN<INFO<DEBUG<TRACE<ALL)

退出应用时的处理

在退出应用时,使用者应当在Ability的onDestroy生命周期中调用LogManager.terminate()来销毁Logger及Appender实例。

约束与限制

在下述版本验证通过:DevEco Studio NEXT Developer Preview 2 (4.1.3.700), SDK: API11 (4.1.0(11))

本库理论上支持所有API版本

贡献代码

开源协议

本项目使用Apache License 2.0

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

轻量、易集成、易使用,有时甚至可以不需写代码的HarmonyOS log系统,灵感来自log4j。 展开 收起
TypeScript 等 3 种语言
Apache-2.0
取消

发行版 (6)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/ericple/log4a.git
git@gitee.com:ericple/log4a.git
ericple
log4a
log4a
master

搜索帮助