AOSP系统沙箱-自实现libc层的log函数

一 /bionic/libc/include/unistd.h 添加

void clogi(const char* method, const char* info);
void cloge(const char* method, const char* error);

二 bionic/libc/async_safe/include/async_safe/log.h添加

#define YOOHA_TAG "YoohaLogC"
#define CLOGI(...) async_safe_format_log(ANDROID_LOG_INFO, YOOHA_TAG, __VA_ARGS__)
#define CLOGE(...) async_safe_format_log(ANDROID_LOG_ERROR, YOOHA_TAG, __VA_ARGS__)

三 创建/bionic/libc/bionic/clog.cpp文件

#include <unistd.h>
#include <async_safe/log.h>
#include <string.h>
#include <stdio.h>


void clogi(const char* method, const char* info){
  int pid = getpid();
  if (pid < 2000){
    return;
  }
  char sPid[16] = {0};

  sprintf(sPid, "\"PID\":\"%d\"", pid);
 
  char sinfo[1024] = {0};
  int lenInfo = strlen(info);
  if (lenInfo > 1023){
    strncpy(sinfo, info, 1023);
    sinfo[1022] = 0;
  }else{
    strcpy(sinfo, info);
    sinfo[lenInfo - 1] = 0;
  }

  CLOGI("{\"Type\":\"NativeLog\",%s,\"Info\":\"<%s>:%s\"}", sPid, method, sinfo);

}

void cloge(const char* method, const char* error){
  int pid = getpid();
  if (pid < 2000){
    return;
  }
  char sPid[16] = {0};

  sprintf(sPid, "\"PID\":\"%d\"", pid);
 
  char sError[1024] = {0};
  int lenError = strlen(error);
  if (lenError > 1023){
    strncpy(sError, error, 1023);
    sError[1022] = 0;
  }else{
    strcpy(sError, error);
    sError[lenError - 1] = 0;
  }

  CLOGE("{\"Type\":\"NativeLog\",%s,\"Info\":\"<%s>:%s\"}", sPid, method, sError);

}

四 添加编译选项  /bionic/libc/Android.bp 添加

cc_library_static {
    defaults: ["libc_defaults"],
    srcs: [
    ...
    "bionic/clog.cpp",   // add start
    ...
    ]
}

五 使用

#include <unistd.h>
 
clogi("func", "test test");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值