TushareClientBuilder

Struct TushareClientBuilder 

Source
pub struct TushareClientBuilder { /* private fields */ }
Expand description

Tushare client builder

Implementations§

Source§

impl TushareClientBuilder

Source

pub fn new() -> Self

Source

pub fn with_token(self, token: &str) -> Self

Examples found in repository?
examples/tracing_example.rs (line 48)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    println!("=== Tushare API Tracing Integration Example ===");
12    
13    // Method 1: Using tracing-log bridge (recommended for mixed ecosystems)
14    #[cfg(all(feature = "tracing", feature = "tracing-log"))] 
15    {
16        println!("\n--- Method 1: Using tracing-log bridge ---");
17        use tracing_subscriber;
18        use tracing_log::LogTracer;
19        
20        // Initialize log-to-tracing bridge
21        LogTracer::init()?;
22        
23        // Set up tracing subscriber
24        tracing_subscriber::fmt()
25            .with_env_filter("debug")
26            .with_target(false)
27            .with_thread_ids(true)
28            .with_level(true)
29            .with_max_level(tracing::Level::DEBUG)
30            .init();
31    }
32    
33    // Method 2: Using native tracing feature (when library is compiled with tracing feature)
34    #[cfg(feature = "tracing")]
35    {
36        println!("\n--- Method 2: Using native tracing feature ---");
37        println!("库和用户程序都使用 tracing\n");
38        
39        // 直接初始化 tracing subscriber
40        tracing_subscriber::fmt()
41            .with_max_level(tracing::Level::DEBUG)
42            .init();
43    }
44
45    println!("初始化 Tushare 客户端...");
46    
47    let client = TushareClient::builder()
48        .with_token("demo_token_for_testing")
49        .with_log_level(LogLevel::Debug)
50        .log_requests(true)
51        .log_responses(false)
52        .log_performance(true)
53        .build()?;
54
55    println!("创建测试请求...");
56    
57    let mut params = HashMap::new();
58    params.insert("list_status".to_string(), "L".to_string());
59    
60    let request = TushareRequest {
61        api_name: Api::StockBasic,
62        params,
63        fields: vec!["ts_code".to_string(), "name".to_string()],
64    };
65
66    println!("发送 API 请求(注意观察日志输出)...");
67    
68    // 这会触发我们库的日志输出
69    match client.call_api(&request).await {
70        Ok(_response) => {
71            println!("✅ API 调用成功(实际会因为 token 无效而失败,但能看到日志)");
72        }
73        Err(e) => {
74            println!("❌ API 调用失败(预期行为): {}", e);
75        }
76    }
77
78    #[cfg(not(feature = "tracing"))]
79    {
80        println!("\n--- Tracing feature not enabled ---");
81        println!("To enable tracing support, compile with: cargo build --features tracing");
82        println!("Or add tracing-log bridge support with: cargo build --features tracing-log");
83    }
84
85    println!("\n=== 总结 ===");
86    #[cfg(feature = "tracing")]
87    println!("✅ 使用了原生 tracing 支持,日志输出更加结构化");
88    
89    #[cfg(not(feature = "tracing"))]
90    println!("✅ 使用了 tracing-log 桥接,成功捕获了库的 log 输出");
91
92    Ok(())
93}
More examples
Hide additional examples
examples/logging_example.rs (line 15)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}
Source

pub fn with_connect_timeout(self, connect_timeout: Duration) -> Self

Examples found in repository?
examples/logging_example.rs (line 34)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}
Source

pub fn with_timeout(self, timeout: Duration) -> Self

Examples found in repository?
examples/logging_example.rs (line 35)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}
Source

pub fn with_http_config(self, http_config: HttpClientConfig) -> Self

Set HTTP client configuration

Source

pub fn with_pool_max_idle_per_host(self, max_idle: usize) -> Self

Set maximum idle connections per host

Source

pub fn with_pool_idle_timeout(self, timeout: Duration) -> Self

Set pool idle timeout

Source

pub fn with_log_config(self, log_config: LogConfig) -> Self

Examples found in repository?
examples/logging_example.rs (line 51)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}
Source

pub fn with_log_level(self, level: LogLevel) -> Self

Set log level

Examples found in repository?
examples/tracing_example.rs (line 49)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    println!("=== Tushare API Tracing Integration Example ===");
12    
13    // Method 1: Using tracing-log bridge (recommended for mixed ecosystems)
14    #[cfg(all(feature = "tracing", feature = "tracing-log"))] 
15    {
16        println!("\n--- Method 1: Using tracing-log bridge ---");
17        use tracing_subscriber;
18        use tracing_log::LogTracer;
19        
20        // Initialize log-to-tracing bridge
21        LogTracer::init()?;
22        
23        // Set up tracing subscriber
24        tracing_subscriber::fmt()
25            .with_env_filter("debug")
26            .with_target(false)
27            .with_thread_ids(true)
28            .with_level(true)
29            .with_max_level(tracing::Level::DEBUG)
30            .init();
31    }
32    
33    // Method 2: Using native tracing feature (when library is compiled with tracing feature)
34    #[cfg(feature = "tracing")]
35    {
36        println!("\n--- Method 2: Using native tracing feature ---");
37        println!("库和用户程序都使用 tracing\n");
38        
39        // 直接初始化 tracing subscriber
40        tracing_subscriber::fmt()
41            .with_max_level(tracing::Level::DEBUG)
42            .init();
43    }
44
45    println!("初始化 Tushare 客户端...");
46    
47    let client = TushareClient::builder()
48        .with_token("demo_token_for_testing")
49        .with_log_level(LogLevel::Debug)
50        .log_requests(true)
51        .log_responses(false)
52        .log_performance(true)
53        .build()?;
54
55    println!("创建测试请求...");
56    
57    let mut params = HashMap::new();
58    params.insert("list_status".to_string(), "L".to_string());
59    
60    let request = TushareRequest {
61        api_name: Api::StockBasic,
62        params,
63        fields: vec!["ts_code".to_string(), "name".to_string()],
64    };
65
66    println!("发送 API 请求(注意观察日志输出)...");
67    
68    // 这会触发我们库的日志输出
69    match client.call_api(&request).await {
70        Ok(_response) => {
71            println!("✅ API 调用成功(实际会因为 token 无效而失败,但能看到日志)");
72        }
73        Err(e) => {
74            println!("❌ API 调用失败(预期行为): {}", e);
75        }
76    }
77
78    #[cfg(not(feature = "tracing"))]
79    {
80        println!("\n--- Tracing feature not enabled ---");
81        println!("To enable tracing support, compile with: cargo build --features tracing");
82        println!("Or add tracing-log bridge support with: cargo build --features tracing-log");
83    }
84
85    println!("\n=== 总结 ===");
86    #[cfg(feature = "tracing")]
87    println!("✅ 使用了原生 tracing 支持,日志输出更加结构化");
88    
89    #[cfg(not(feature = "tracing"))]
90    println!("✅ 使用了 tracing-log 桥接,成功捕获了库的 log 输出");
91
92    Ok(())
93}
More examples
Hide additional examples
examples/logging_example.rs (line 22)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}
Source

pub fn log_requests(self, enabled: bool) -> Self

Enable or disable request logging

Examples found in repository?
examples/tracing_example.rs (line 50)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    println!("=== Tushare API Tracing Integration Example ===");
12    
13    // Method 1: Using tracing-log bridge (recommended for mixed ecosystems)
14    #[cfg(all(feature = "tracing", feature = "tracing-log"))] 
15    {
16        println!("\n--- Method 1: Using tracing-log bridge ---");
17        use tracing_subscriber;
18        use tracing_log::LogTracer;
19        
20        // Initialize log-to-tracing bridge
21        LogTracer::init()?;
22        
23        // Set up tracing subscriber
24        tracing_subscriber::fmt()
25            .with_env_filter("debug")
26            .with_target(false)
27            .with_thread_ids(true)
28            .with_level(true)
29            .with_max_level(tracing::Level::DEBUG)
30            .init();
31    }
32    
33    // Method 2: Using native tracing feature (when library is compiled with tracing feature)
34    #[cfg(feature = "tracing")]
35    {
36        println!("\n--- Method 2: Using native tracing feature ---");
37        println!("库和用户程序都使用 tracing\n");
38        
39        // 直接初始化 tracing subscriber
40        tracing_subscriber::fmt()
41            .with_max_level(tracing::Level::DEBUG)
42            .init();
43    }
44
45    println!("初始化 Tushare 客户端...");
46    
47    let client = TushareClient::builder()
48        .with_token("demo_token_for_testing")
49        .with_log_level(LogLevel::Debug)
50        .log_requests(true)
51        .log_responses(false)
52        .log_performance(true)
53        .build()?;
54
55    println!("创建测试请求...");
56    
57    let mut params = HashMap::new();
58    params.insert("list_status".to_string(), "L".to_string());
59    
60    let request = TushareRequest {
61        api_name: Api::StockBasic,
62        params,
63        fields: vec!["ts_code".to_string(), "name".to_string()],
64    };
65
66    println!("发送 API 请求(注意观察日志输出)...");
67    
68    // 这会触发我们库的日志输出
69    match client.call_api(&request).await {
70        Ok(_response) => {
71            println!("✅ API 调用成功(实际会因为 token 无效而失败,但能看到日志)");
72        }
73        Err(e) => {
74            println!("❌ API 调用失败(预期行为): {}", e);
75        }
76    }
77
78    #[cfg(not(feature = "tracing"))]
79    {
80        println!("\n--- Tracing feature not enabled ---");
81        println!("To enable tracing support, compile with: cargo build --features tracing");
82        println!("Or add tracing-log bridge support with: cargo build --features tracing-log");
83    }
84
85    println!("\n=== 总结 ===");
86    #[cfg(feature = "tracing")]
87    println!("✅ 使用了原生 tracing 支持,日志输出更加结构化");
88    
89    #[cfg(not(feature = "tracing"))]
90    println!("✅ 使用了 tracing-log 桥接,成功捕获了库的 log 输出");
91
92    Ok(())
93}
More examples
Hide additional examples
examples/logging_example.rs (line 30)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}
Source

pub fn log_responses(self, enabled: bool) -> Self

Enable or disable response logging

Examples found in repository?
examples/tracing_example.rs (line 51)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    println!("=== Tushare API Tracing Integration Example ===");
12    
13    // Method 1: Using tracing-log bridge (recommended for mixed ecosystems)
14    #[cfg(all(feature = "tracing", feature = "tracing-log"))] 
15    {
16        println!("\n--- Method 1: Using tracing-log bridge ---");
17        use tracing_subscriber;
18        use tracing_log::LogTracer;
19        
20        // Initialize log-to-tracing bridge
21        LogTracer::init()?;
22        
23        // Set up tracing subscriber
24        tracing_subscriber::fmt()
25            .with_env_filter("debug")
26            .with_target(false)
27            .with_thread_ids(true)
28            .with_level(true)
29            .with_max_level(tracing::Level::DEBUG)
30            .init();
31    }
32    
33    // Method 2: Using native tracing feature (when library is compiled with tracing feature)
34    #[cfg(feature = "tracing")]
35    {
36        println!("\n--- Method 2: Using native tracing feature ---");
37        println!("库和用户程序都使用 tracing\n");
38        
39        // 直接初始化 tracing subscriber
40        tracing_subscriber::fmt()
41            .with_max_level(tracing::Level::DEBUG)
42            .init();
43    }
44
45    println!("初始化 Tushare 客户端...");
46    
47    let client = TushareClient::builder()
48        .with_token("demo_token_for_testing")
49        .with_log_level(LogLevel::Debug)
50        .log_requests(true)
51        .log_responses(false)
52        .log_performance(true)
53        .build()?;
54
55    println!("创建测试请求...");
56    
57    let mut params = HashMap::new();
58    params.insert("list_status".to_string(), "L".to_string());
59    
60    let request = TushareRequest {
61        api_name: Api::StockBasic,
62        params,
63        fields: vec!["ts_code".to_string(), "name".to_string()],
64    };
65
66    println!("发送 API 请求(注意观察日志输出)...");
67    
68    // 这会触发我们库的日志输出
69    match client.call_api(&request).await {
70        Ok(_response) => {
71            println!("✅ API 调用成功(实际会因为 token 无效而失败,但能看到日志)");
72        }
73        Err(e) => {
74            println!("❌ API 调用失败(预期行为): {}", e);
75        }
76    }
77
78    #[cfg(not(feature = "tracing"))]
79    {
80        println!("\n--- Tracing feature not enabled ---");
81        println!("To enable tracing support, compile with: cargo build --features tracing");
82        println!("Or add tracing-log bridge support with: cargo build --features tracing-log");
83    }
84
85    println!("\n=== 总结 ===");
86    #[cfg(feature = "tracing")]
87    println!("✅ 使用了原生 tracing 支持,日志输出更加结构化");
88    
89    #[cfg(not(feature = "tracing"))]
90    println!("✅ 使用了 tracing-log 桥接,成功捕获了库的 log 输出");
91
92    Ok(())
93}
More examples
Hide additional examples
examples/logging_example.rs (line 31)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}
Source

pub fn log_sensitive_data(self, enabled: bool) -> Self

Enable or disable sensitive data logging

Examples found in repository?
examples/logging_example.rs (line 32)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}
Source

pub fn log_performance(self, enabled: bool) -> Self

Enable or disable performance metrics logging

Examples found in repository?
examples/tracing_example.rs (line 52)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    println!("=== Tushare API Tracing Integration Example ===");
12    
13    // Method 1: Using tracing-log bridge (recommended for mixed ecosystems)
14    #[cfg(all(feature = "tracing", feature = "tracing-log"))] 
15    {
16        println!("\n--- Method 1: Using tracing-log bridge ---");
17        use tracing_subscriber;
18        use tracing_log::LogTracer;
19        
20        // Initialize log-to-tracing bridge
21        LogTracer::init()?;
22        
23        // Set up tracing subscriber
24        tracing_subscriber::fmt()
25            .with_env_filter("debug")
26            .with_target(false)
27            .with_thread_ids(true)
28            .with_level(true)
29            .with_max_level(tracing::Level::DEBUG)
30            .init();
31    }
32    
33    // Method 2: Using native tracing feature (when library is compiled with tracing feature)
34    #[cfg(feature = "tracing")]
35    {
36        println!("\n--- Method 2: Using native tracing feature ---");
37        println!("库和用户程序都使用 tracing\n");
38        
39        // 直接初始化 tracing subscriber
40        tracing_subscriber::fmt()
41            .with_max_level(tracing::Level::DEBUG)
42            .init();
43    }
44
45    println!("初始化 Tushare 客户端...");
46    
47    let client = TushareClient::builder()
48        .with_token("demo_token_for_testing")
49        .with_log_level(LogLevel::Debug)
50        .log_requests(true)
51        .log_responses(false)
52        .log_performance(true)
53        .build()?;
54
55    println!("创建测试请求...");
56    
57    let mut params = HashMap::new();
58    params.insert("list_status".to_string(), "L".to_string());
59    
60    let request = TushareRequest {
61        api_name: Api::StockBasic,
62        params,
63        fields: vec!["ts_code".to_string(), "name".to_string()],
64    };
65
66    println!("发送 API 请求(注意观察日志输出)...");
67    
68    // 这会触发我们库的日志输出
69    match client.call_api(&request).await {
70        Ok(_response) => {
71            println!("✅ API 调用成功(实际会因为 token 无效而失败,但能看到日志)");
72        }
73        Err(e) => {
74            println!("❌ API 调用失败(预期行为): {}", e);
75        }
76    }
77
78    #[cfg(not(feature = "tracing"))]
79    {
80        println!("\n--- Tracing feature not enabled ---");
81        println!("To enable tracing support, compile with: cargo build --features tracing");
82        println!("Or add tracing-log bridge support with: cargo build --features tracing-log");
83    }
84
85    println!("\n=== 总结 ===");
86    #[cfg(feature = "tracing")]
87    println!("✅ 使用了原生 tracing 支持,日志输出更加结构化");
88    
89    #[cfg(not(feature = "tracing"))]
90    println!("✅ 使用了 tracing-log 桥接,成功捕获了库的 log 输出");
91
92    Ok(())
93}
More examples
Hide additional examples
examples/logging_example.rs (line 33)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}
Source

pub fn build(self) -> TushareResult<TushareClient>

Examples found in repository?
examples/tracing_example.rs (line 53)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    println!("=== Tushare API Tracing Integration Example ===");
12    
13    // Method 1: Using tracing-log bridge (recommended for mixed ecosystems)
14    #[cfg(all(feature = "tracing", feature = "tracing-log"))] 
15    {
16        println!("\n--- Method 1: Using tracing-log bridge ---");
17        use tracing_subscriber;
18        use tracing_log::LogTracer;
19        
20        // Initialize log-to-tracing bridge
21        LogTracer::init()?;
22        
23        // Set up tracing subscriber
24        tracing_subscriber::fmt()
25            .with_env_filter("debug")
26            .with_target(false)
27            .with_thread_ids(true)
28            .with_level(true)
29            .with_max_level(tracing::Level::DEBUG)
30            .init();
31    }
32    
33    // Method 2: Using native tracing feature (when library is compiled with tracing feature)
34    #[cfg(feature = "tracing")]
35    {
36        println!("\n--- Method 2: Using native tracing feature ---");
37        println!("库和用户程序都使用 tracing\n");
38        
39        // 直接初始化 tracing subscriber
40        tracing_subscriber::fmt()
41            .with_max_level(tracing::Level::DEBUG)
42            .init();
43    }
44
45    println!("初始化 Tushare 客户端...");
46    
47    let client = TushareClient::builder()
48        .with_token("demo_token_for_testing")
49        .with_log_level(LogLevel::Debug)
50        .log_requests(true)
51        .log_responses(false)
52        .log_performance(true)
53        .build()?;
54
55    println!("创建测试请求...");
56    
57    let mut params = HashMap::new();
58    params.insert("list_status".to_string(), "L".to_string());
59    
60    let request = TushareRequest {
61        api_name: Api::StockBasic,
62        params,
63        fields: vec!["ts_code".to_string(), "name".to_string()],
64    };
65
66    println!("发送 API 请求(注意观察日志输出)...");
67    
68    // 这会触发我们库的日志输出
69    match client.call_api(&request).await {
70        Ok(_response) => {
71            println!("✅ API 调用成功(实际会因为 token 无效而失败,但能看到日志)");
72        }
73        Err(e) => {
74            println!("❌ API 调用失败(预期行为): {}", e);
75        }
76    }
77
78    #[cfg(not(feature = "tracing"))]
79    {
80        println!("\n--- Tracing feature not enabled ---");
81        println!("To enable tracing support, compile with: cargo build --features tracing");
82        println!("Or add tracing-log bridge support with: cargo build --features tracing-log");
83    }
84
85    println!("\n=== 总结 ===");
86    #[cfg(feature = "tracing")]
87    println!("✅ 使用了原生 tracing 支持,日志输出更加结构化");
88    
89    #[cfg(not(feature = "tracing"))]
90    println!("✅ 使用了 tracing-log 桥接,成功捕获了库的 log 输出");
91
92    Ok(())
93}
More examples
Hide additional examples
examples/logging_example.rs (line 16)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // 注意:在实际使用中,您需要初始化一个日志记录器(如 env_logger)
8    // env_logger::init();
9
10    println!("=== Tushare API 日志功能演示 ===\n");
11
12    // 示例 1: 使用默认日志配置
13    println!("1. 使用默认日志配置:");
14    let client1 = TushareClient::builder()
15        .with_token("your_token_here")
16        .build()?;
17
18    // 示例 2: 自定义日志级别
19    println!("\n2. 自定义日志级别为 Debug:");
20    let client2 = TushareClient::builder()
21        .with_token("your_token_here")
22        .with_log_level(LogLevel::Debug)
23        .build()?;
24
25    // 示例 3: 详细的日志配置
26    println!("\n3. 详细的日志配置:");
27    let client3 = TushareClient::builder()
28        .with_token("your_token_here")
29        .with_log_level(LogLevel::Trace)
30        .log_requests(true)
31        .log_responses(true)
32        .log_sensitive_data(false) // 生产环境建议设为 false
33        .log_performance(true)
34        .with_connect_timeout(Duration::from_secs(5))
35        .with_timeout(Duration::from_secs(30))
36        .build()?;
37
38    // 示例 4: 使用自定义 LogConfig
39    println!("\n4. 使用自定义 LogConfig:");
40    let log_config = LogConfig {
41        level: LogLevel::Info,
42        log_requests: true,
43        log_responses: false,
44        log_responses_err: true,
45        log_sensitive_data: false,
46        log_performance: true,
47    };
48    
49    let client4 = TushareClient::builder()
50        .with_token("your_token_here")
51        .with_log_config(log_config)
52        .build()?;
53
54    // 示例 5: 关闭日志
55    println!("\n5. 关闭日志:");
56    let client5 = TushareClient::builder()
57        .with_token("your_token_here")
58        .with_log_level(LogLevel::Off)
59        .build()?;
60
61    // 演示 API 调用(需要有效的 token)
62    if std::env::var("TUSHARE_TOKEN").is_ok() {
63        println!("\n=== 实际 API 调用演示 ===");
64        
65        let client = TushareClient::builder()
66            .with_token(&std::env::var("TUSHARE_TOKEN")?)
67            .with_log_level(LogLevel::Info)
68            .log_performance(true)
69            .build()?;
70
71        let mut params = HashMap::new();
72        params.insert("list_status".to_string(), "L".to_string());
73        
74        let req = TushareRequest {
75            api_name: Api::StockBasic,
76            params,
77            fields: vec!["ts_code".to_string(), "name".to_string()],
78        };
79
80        match client.call_api(&req).await {
81            Ok(response) => {
82                if let Some(data) = response.data {
83                    println!("✅ API 调用成功,返回 {} 条记录", data.items.len());
84                }
85            }
86            Err(e) => {
87                println!("❌ API 调用失败: {}", e);
88            }
89        }
90    } else {
91        println!("\n💡 提示: 设置 TUSHARE_TOKEN 环境变量以查看实际的 API 调用日志");
92    }
93
94    println!("\n=== 日志级别说明 ===");
95    println!("• Off    - 关闭所有日志");
96    println!("• Error  - 只记录错误信息");
97    println!("• Warn   - 记录错误和警告");
98    println!("• Info   - 记录基本信息(推荐)");
99    println!("• Debug  - 记录详细调试信息");
100    println!("• Trace  - 记录所有信息包括原始数据");
101
102    println!("\n=== 日志配置选项说明 ===");
103    println!("• log_requests      - 是否记录请求参数");
104    println!("• log_responses     - 是否记录响应内容(可能很大)");
105    println!("• log_sensitive_data - 是否记录敏感数据(如 token)");
106    println!("• log_performance   - 是否记录性能指标(耗时等)");
107
108    Ok(())
109}

Trait Implementations§

Source§

impl Debug for TushareClientBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,