> For the complete documentation index, see [llms.txt](https://54td.gitbook.io/shence/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://54td.gitbook.io/shence/technical_guide/import_tool/log_agent/log_agent_scene.md).

# LogAgent 场景使用示例

## 1. 生成数据

### 1.1 使用神策分析 SDK 生成数据文件

神策分析各后端语言的 SDK 都支持将数据写入文件，例如使用 [Java SDK](/shence/technical_guide/detailed_guide_server/java_sdk.md) 的 `ConcurrentLoggingConsumer`，[PHP SDK](/shence/technical_guide/detailed_guide_server/php_sdk.md) 的 `FileConsumer`，[Python SDK](/shence/technical_guide/detailed_guide_server/python_sdk.md) 的 `LoggingConsumer`。下面以 Java SDK 为例：

```java
// 使用 ConcurrentLoggingConsumer 初始化 SensorsAnalytics
// 将数据输出到 /data/sa 下的 service_log.2017-09-25 文件中，每天一个文件
final SensorsAnalytics sa = new SensorsAnalytics(
        new SensorsAnalytics.ConcurrentLoggingConsumer("/data/sa/service_log")); 

// 使用神策分析记录用户行为数据
sa.track(distinctId, true, "UserLogin");
sa.track(distinctId, true, "ViewProduct");

// 程序结束前，停止神策分析 SDK 所有服务
sa.shutdown();
```

以上配置将在 `/data/sa` 目录下生成数据文件，一天一个文件，文件列表如：

```
service_log.20170923
service_log.20170924
service_log.20170925
```

对应 LogAgent 中的配置：

```
path=/data/sa
pattern=service_log.*
```

### 1.2 使用其他方式输出数据文件

若所使用的编程语言有对应的 SDK，建议直接使用 SDK 来输出数据文件；若需要自己写数据文件，有几点需要注意：

1. （非常重要）文件只能追加写入，即打开文件时以 Open Append 方式打开；
2. 文件内容需要是 **一条数据一行**，并且是符合[数据格式](/shence/technical_guide/data_import/data_schema.md)的完整 JSON；
3. 数据文件名 **必须** 包含日期，还可以包含更详细的时间，例如将数据写到 `service_log.20170925` 或 `service_log.2017092517`，文件目录下文件应该类似如下：

   ```
   service_log.20170923
   service_log.20170924
   service_log.20170925
   ```

   对应 LogAgent 中的配置：

   ```
   path=/data/sa
   pattern=service_log.*
   ```
4. 若多个进程写入同一个文件，需要使用文件锁避免文件交叉写入数据损坏；

## 2. 配置数据接收服务地址

### 2.1 私有部署版配置

LogAgent 将数据发送到服务端，至少需要配置接收数据的服务端地址，对应配置文件中 `host` 和 `port` 两个参数：

* host：`一个` 或 `多个以 ; 半角分号分隔的服务器 IP 地址`。例如 `192.168.50.10;192.168.50.11;192.168.50.12`，LogAgent 启动时会选定其中一台发送数据，以均衡负载；
* port：数据接收服务端口号，默认情况下集群版是 8106，单机版（1.7 及之前的版本为 8006，1.8 及之后的版本是 8106），云版不带端口号； &#x20;

若部署神策分析同时有外网 IP 和 内网 IP，host 的值应取内网 IP;

### 2.2 云版配置

点击“复制 https 数据接收地址”，例如复制到的是 `https://example.datasink.sensorsdata.cn/sa?project=production&token=c9239cb3139077ca`

在配置文件中，请删除或注释掉 `host`、`port` 和 `token` 字段，启用 `service_uri` 字段，取值是将上面获取到的值中的 `/sa` 改为 `/log_agent`，例如对于上面样例，应配置 `https://example.datasink.sensorsdata.cn/log_agent?token=c9239cb3139077ca`。

* 指定数据发往的项目请参考本文档 4.1 节。

### 2.3 通过外网使用额外需要注意的配置

LogAgent 是为内网后端实时数据导入设计开发，若通过公网使用 LogAgent 需要额外注意：

* **请确保一个 LogAgent 每次请求都落到同一台机器上**。如果使用负载均衡，负载均衡算法请选择 `ip_hash 源地址` 方式；如果域名 DNS 直接解析到多台机器，则不能使用域名，应直接指定一个 IP 或按上面规则拼接多个服务器的外网 IP；
* 若公网使用 LogAgent 且服务端已经配置了 HTTPS 数据接入方式，可以按如下步骤配置使用 HTTPS 发送数据：
  1. 注释掉配置文件中的 `host`、`port` 和 `token` 字段，即不使用 `host`、`port` 和 `token` 参数；
  2. 在配置文件中启用 `service_uri` 字段，一个样例值为 `https://example.sensorsdata.cn:4006/log_agent`，请注意端口号应为 HTTPS 数据接入服务的地址，`uri` 是 `/log_agent`，而不是 `/sa`;

## 3. 其他配置说明

### 3.1 配置实时写入文件的文件名 `real_time_file_name`

配置文件中的 `real_time_file_name` 即实时写入文件的文件名, 一般用在滚动日志文件的场景。例如按日切分的数据目录下文件列表如下：

```
service_log.20170922
service_log.20170923
service_log
```

数据输出进程只向 `service_log` 中写入，当到了新的一天，定时调度程序将 `service_log` 改名为带日期的文件例如 `service_log.20170923`，数据输出进程开始写一个新的 `service_log` 文件，在这个场景里配置应当是:

```
pattern=service_log.*
real_time_file_name=service_log
```

即 `pattern` 可以匹配所有改名后的数据文件名，而 `real_time_file_name` 为实时输出的数据文件名。

## 4. 其他使用场景说明

### 4.1 指定数据导入项目

指定数据导入的项目有两种方法：

1. 在每条数据中添加 `project` 字段（详见[数据格式](/shence/technical_guide/data_import/data_schema.md)），使用这种方式可以每条数据导入各自的项目；
2. 在配置文件中指定 `project`。每条数据无论是否指定 `project` 字段都将导入到参数设置的项目中。

系统判定一条数据所属项目的流程为：

1. 取配置文件中的 `project`；
2. 若上一步没有取到，取数据中的 `project` 字段；
3. 若上一步没有取到，（若有配置）取 `service_uri` 的 `project` 参数；
4. 若上一步没有取到，取默认项目的项目名，即 `default`。

如果想用一个 LogAgent 导入多个项目的数据，请不要在配置文件中设置 `project`，在数据中添加 `project` 字段来设置每条数据所属项目。

### 4.2 使用 `file-list-tool` 列出文件读取情况

新版本 LogAgent 提供了 `file-list-tool`：

```bash
$ bin/file-list-tool
usage: [file-checker] --context_file <arg> [-h] [--new_file_format <arg>]
       [--old_file_format <arg>] [--reading_file_format <arg>]
    --context_file <arg>          LogAgent context file path, e.g.
                                  logagent.pid.context
 -h,--help                        help
    --new_file_format <arg>       对每个未读过的新文件的输出格式，指定后会格式化并输出，文件名以 {} 代替
    --old_file_format <arg>       对每个旧文件的输出格式，指定后会格式化并输出，文件名以 {} 代替
    --reading_file_format <arg>   对正在读取的文件的输出格式，指定后会格式化并输出，文件名以 {} 代替
```

使用 `file-list-tool` 解析 `context` 文件（与 `pid` 文件在同一个目录下）可以列出每个文件的读取状态：

```bash
$ bin/file-list-tool --context_file logagent.pid.context
18/01/22 17:35:29 INFO logagent.SourceFileReader: SourceFileReader recover progress:
[ fileKey: (dev=fc10,ino=118226959), offset: 11260636, fileName: test_data.2018012213, count: 161982, sourceCount: 161982 ]
18/01/22 17:35:29 INFO logagent.FileListTool: 进度之前的文件, path: /data/test/logagent/data/test_data.2018012212, size: 19191980, key: (dev=fc10,ino=118226958)
18/01/22 17:35:29 INFO logagent.FileListTool: 读取中的文件, path: /data/test/logagent/data/test_data.2018012213, size: 11260824, key: (dev=fc10,ino=118226959), tell: 11260636
18/01/22 17:35:29 INFO logagent.FileListTool: 进度之后的文件, path: /data/test/logagent/data/test_data.2018012214, size: 19191980, key: (dev=fc10,ino=118226960)
```

“进度之前的文件” 即已经读取过的可以安全地从 LogAgent 读取目录移走或删除的文件。

`file-list-tool` 还可以以指定格式输出文件列表，例如下面的例子生成将已经读取过的文件移到指定目录的命令文件 mv.sh 并执行：

```bash
$ bin/file-list-tool --context_file logagent.pid.context --old_file_format 'mv {} /data/test/logagent/backup' > mv.sh
18/01/22 17:44:29 INFO logagent.SourceFileReader: SourceFileReader recover progress:
[ fileKey: (dev=fc10,ino=118226959), offset: 11260636, fileName: test_data.2018012213, count: 161982, sourceCount: 161982 ]
18/01/22 17:44:29 INFO logagent.FileListTool: 进度之前的文件, path: /data/test/logagent/data/test_data.2018012212, size: 19191980, key: (dev=fc10,ino=118226958)
18/01/22 17:44:29 INFO logagent.FileListTool: 读取中的文件, path: /data/test/logagent/data/test_data.2018012213, size: 11260824, key: (dev=fc10,ino=118226959), tell: 11260636
18/01/22 17:44:29 INFO logagent.FileListTool: 进度之后的文件, path: /data/test/logagent/data/test_data.2018012214, size: 19191980, key: (dev=fc10,ino=118226960)

$ cat mv.sh
mv /data/test/logagent/data/test_data.2018012212 /data/test/logagent/backup

$ bash mv.sh
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://54td.gitbook.io/shence/technical_guide/import_tool/log_agent/log_agent_scene.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
