CatchLog log信息捕捉

本文介绍如何在Android应用程序中使用Logcat获取日志信息,并通过Broadcast发送更新的日志内容到MainActivity。主要内容包括:在AndroidManifest.xml中添加权限、通过Service启动logcat进程、实时读取并处理日志信息、利用Broadcast将日志内容传递给MainActivity。

一定一定要添加权限!!!

  1. <uses-permission android:name="android.permission.READ_LOGS" />  


通过启动另一个service来获取log信息。并通过broadcast 发送log信息。

public void run() {
		// TODO Auto-generated method stub
		System.out.println("the function run() is running.");
		Process pro = null;
		String line=null;
		try{
			//Runtime.getRuntime().exec("logcat -d");
			pro= Runtime.getRuntime().exec(new String[] {"logcat","*:I"});
			BufferedReader br= new BufferedReader(new InputStreamReader(pro.getInputStream()));
			while(isCatchLog){
				if((line=br.readLine())!=null){
					logContentsArrayList.add(line);
					sendLogContent(logContentsArrayList);
					Thread.sleep(1000);
				}else{
					System.out.println("readline() is null");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

mainactivity从broadcast里获取intent,从而取得bundle内的log信息。

private class LogBroadcastReceiver extends BroadcastReceiver {     
		private String action = null;
		private Bundle bundle = null;

		@Override
		public void onReceive(Context context, Intent intent) {
			action = intent.getAction();
			if (LOG_ACTION.equals(action)) {
				bundle = intent.getExtras();
				ArrayList<String> logArrayList = bundle
						.getStringArrayList("log");
				adapter = new ArrayAdapter<String>(MainActivity.this,
						android.R.layout.simple_list_item_1, logArrayList);
				logListView.setAdapter(adapter);
				/*String[] logs = new String[logArrayList.size()];           //log存储
				logs = logArrayList.toArray(logs);
				if (logs.length > 0) {
					for (int i = 0; i < logs.length; i++) {
						logString.append(logs[i]);
						logString.append("\n");
					}
				}

				try {
					fileService.saveToSDCard("/log.txt", logString.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}*/
			}
		}
	}
	private void registerLogBroadcastReceiver() {
		logBroadcastReceiver = new LogBroadcastReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(LOG_ACTION);
		registerReceiver(logBroadcastReceiver, filter);
		//System.out.println("register logBroadcastReceiver");
	}


在使用 `pytest` 生成日志文件时,日志文件为空是一个较为常见的问题。该问题通常与日志级别配置、日志捕获机制或插件兼容性有关。以下是一些可能的原因及对应的解决方法。 ### 日志级别配置问题 `pytest` 默认不会捕获所有日志信息,除非明确配置。例如,如果测试代码中使用 `logging.info()`,但 `pytest` 的日志级别未设置为 `INFO` 或更低级别(如 `DEBUG`),则这些日志信息不会被记录到文件中。可以通过在 `pytest.ini` 文件中设置 `log_level` 来解决此问题: ```ini [pytest] log_cli = true log_level = INFO log_file = ./logs/test.log log_file_level = INFO ``` 上述配置确保了 `INFO` 级别的日志信息会被捕获并写入到指定的日志文件中 [^3]。 ### 日志捕获机制问题 `pytest` 提供了内置的日志捕获功能,但有时需要额外的插件来增强日志处理能力。例如,`pytest-catchlog` 插件可以提供更强大的日志捕获功能。安装并启用该插件后,可以在测试用例中使用 `caplog` fixture 来访问日志信息: ```bash pip install pytest-catchlog ``` 在测试用例中使用 `caplog`: ```python def test_example(caplog): import logging logging.getLogger().info("这是一个测试日志") assert "这是一个测试日志" in caplog.text ``` ### 插件兼容性问题 某些情况下,`pytest` 插件之间可能存在兼容性问题,导致日志信息未能正确写入文件。例如,`pytest-html` 插件用于生成 HTML 报告,但如果不正确配置,可能无法将日志信息包含在报告中。可以通过在 `pytest.ini` 文件中添加以下配置来确保日志信息被包含在报告中: ```ini [pytest] log_cli = true log_cli_level = INFO log_cli_format = %(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s log_cli_date_format = %Y-%m-%d %H:%M:%S log_format = %(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)4s: %(message)s log_date_format = %Y-%m-%d %H:%M:%S ``` 此外,运行测试时需要指定生成 HTML 报告的参数: ```bash pytest -s -vv test_case.py --html=./report/report.html ``` ### 自定义日志文件名 如果希望日志文件名包含日期后缀,可以通过自定义插件实现。在 `conftest.py` 文件中定义一个插件,动态生成带有日期后缀的日志文件名: ```python import pytest from datetime import datetime def pytest_configure(config): # 获取当前时间并格式化 now = datetime.now().strftime("%Y%m%d%H%M%S") # 设置日志文件名 config.option.log_file = f"./logs/auto_test_{now}.log" ``` 此插件会在每次运行测试时动态生成一个新的日志文件名,确保每次测试的日志文件都是唯一的 [^1]。 ### 总结 1. **检查日志级别配置**:确保 `pytest.ini` 文件中配置的日志级别足够低,以捕获所需的日志信息。 2. **使用 `pytest-catchlog` 插件**:增强日志捕获功能,确保日志信息能够被正确记录。 3. **检查插件兼容性**:确保使用的插件(如 `pytest-html`)与 `pytest` 的版本兼容,并正确配置。 4. **自定义日志文件名**:通过编写自定义插件动态生成带有日期后缀的日志文件名。 通过以上方法,可以有效解决 `pytest` 生成的日志文件为空的问题。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值