云日志服务Java SDK 3. SDK基本使用 3.1. 基本使用 使用 SDK访问 LTS 的服务,需要设置正确的 AccessKey、SecretKey 和服务端 Endpoint,所有的服务可以使用同一 key 凭证来进行访问,但不同的服务需要使用不同的 endpoint 进行访问,详情参考天翼云官网SDK接入概述。在调用前SDK,需要已知以下参数: 1、云日志服务访问地址。详情请查看访问地址(Endpoint)。 2、key凭证:accessKey和secretKey 。详情请查看如何获取访问密钥(AK/SK)。 3、日志项目编码:logProject,在使用SDK前,需要确保您有至少一个已经存在的日志项目,日志项目就是您要将日志上传到的地方。 4、日志单元编码:logUnit,在使用SDK前,需要确保日志项目中有至少一个已经存在的日志单元。 参数 参数类型 描述 是否必须 endpoint string 域名 是 accessKey string AccessKey,简称ak 是 secretKey string SecretKey ,简称sk 是 logProject string 日志项目编码 是 logUnit string 日志单元编码 是 目前通过SDK将日志上传到云日志服务有两种上传形式:同步上传和异步上传,详细文档参考代码内README文件。 1、同步上传:当调用日志上传接口时,sdk会立即进行http请求调用,并返回发送结果。这种方式结构简单,可用于发送频率不高的场景。 2、异步上传:当调用日志上传接口时,后台线程会将日志进行累积,当达到发送条件时,会进行一次合并发送。对于需要频繁调用发送接口的场景,这种方式性能更卓越,更高效。 示例代码:同步上传 plaintext public static void main(String args[]) throws LogException, InterruptedException { String accessKey "your accessKey"; String secretKey "your secretKey"; String logProject "log project Code";//日志项目ID String logUnit "log unit Code";//日志单元ID String endpoint "endpoint"; Client client new Client(endpoint, accessKey,secretKey); //构建日志 LogItem logItem new LogItem(System.currentTimeMillis()); logItem.setOriginmsg("info: sync ,java, test message!"); //日志原文 logItem.PushBackContent("level", "info"); //日志分词 logItem.PushBackContent("doublenumber", 3.1415); LogItems logItems new LogItems(); logItems.add(logItem); //添加日志,可添加多条 try { for (int i 0; i < 100; i++) { //发送100次 PutLogsResponse response client.PutLogs(logProject, logUnit, logItems); PutLogsResponseBody res response.getBody(); System.out.println("response: statusCode:"+res.getStatusCode()+" ,message:"+res.getMessage()+" ,error:"+res.getError()); } } catch (LogException e) { System.out.println("error :" + e.getErrorCode() + " , " + e.getMessage() + " , " + e.getHttpCode()); e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } 示例代码:异步批量上传 plaintext public static void main(String[] args) throws Exception { String accessKey "your accessKey"; String secretKey "your secretKey"; String logProject "log project Code";//日志项目ID String logUnit "log unit Code";//日志单元ID String endpoint "endpoint"; // 初始化日志生产者 try { Producer producer new LogProducer(new ProducerConfig()); producer.buildClient(logProject, endpoint, accessKey, secretKey); //发送日志,后台自动异步批量发送 for (int i 0; i < 1000; i++) { LogItem logItem Utils.generateLogItem(1); producer.sendLogs(logProject, logUnit, logItem); } // 稍作等待后关闭生产者 Thread.sleep(10000); producer.close(); } catch (InterruptedException e) { LOGGER.warn("关闭生产者时线程被中断"); } catch (ProducerException e) { LOGGER.info("关闭生产者失败: ", e); } catch (Exception e) { LOGGER.info("发生异常: ", e); } }
来自: