Commit 1dfd0433 authored by Alex朱枝文's avatar Alex朱枝文

RN初始化

parent d5d3eee0
export NODE_BINARY=$(command -v node)
export NODE_BINARY=/usr/local/Cellar/node/23.4.0/bin/node
################################################################################################################################
##################################################### podspec file for dev #####################################################
################################################################################################################################
Pod::Spec.new do |s|
s.name = 'AliyunLogProducer'
s.version = "4.3.4"
s.summary = 'aliyun log service ios producer.'
s.description = <<-DESC
log service ios producer.
https://help.aliyun.com/document_detail/29063.html
https://help.aliyun.com/product/28958.html
DESC
s.homepage = 'https://github.com/aliyun/aliyun-log-ios-sdk'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'aliyun-log' => 'yulong.gyl@alibaba-inc.com' }
s.source = { :git => 'https://gitee.com/aliyun-sls/aliyun-log-ios-sdk.git', :tag => s.version.to_s }
s.social_media_url = 'http://t.cn/AiRpol8C'
# s.ios.deployment_target = '10.0'
# s.osx.deployment_target = '10.12'
# s.tvos.deployment_target = '10.0'
s.platform = :ios, "10.0"
s.requires_arc = true
s.libraries = 'z'
s.swift_version = "5.0"
# s.xcconfig = { 'GCC_ENABLE_CPP_EXCEPTIONS' => 'YES' }
# s.default_subspec = 'Producer'
s.pod_target_xcconfig = {
'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64 i386',
}
s.user_target_xcconfig = {
'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64 i386'
}
s.ios.deployment_target = '10.0'
s.tvos.deployment_target = '10.0'
s.osx.deployment_target = '10.12'
s.source_files = 'Sources/Producer/**/*.{h,m}', 'Sources/aliyun-log-c-sdk/**/*.{c,h}'
s.public_header_files = 'Sources/Producer/include/*.h', 'Sources/aliyun-log-c-sdk/include/*.h'
s.resource_bundles = { s.name => ['Sources/Producer/PrivacyInfo.xcprivacy'] }
end
//
// AliyunLog.m
// AliyunLogProducer
//
// Created by lichao on 2020/9/27.
// Copyright © 2020 lichao. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AliyunLog.h"
#import "TimeUtils.h"
#import "SLSProducer.h"
@interface AliyunLog ()
@property (nonatomic, assign) unsigned int logTime;
@property (nonatomic, strong) NSMutableDictionary *content;
- (BOOL) checkValue: (NSString *)value;
@end
@implementation AliyunLog
- (id) init
{
if (self = [super init])
{
_logTime = (unsigned int) [TimeUtils getTimeInMilliis];
_content = [NSMutableDictionary dictionary];
}
return self;
}
+ (instancetype) log {
return [[AliyunLog alloc] init];
}
- (BOOL) checkValue:(NSString *)value {
return value && [value isKindOfClass:[NSString class]];
}
- (void)PutContent:(NSString *) key value:(NSString *)value
{
[self putContent:key value:value];
}
- (void) putContent: (NSString *) key value: (NSString *) value {
if ([self checkValue:key] && [self checkValue:value]) {
[_content setObject:value forKey:key];
}
}
- (BOOL) putContents: (NSDictionary *) dict {
if (!dict) {
return NO;
}
NSDictionary *tmp = [NSDictionary dictionaryWithDictionary:dict];
NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
BOOL error = NO;
id value = nil;
for (id key in tmp.allKeys) {
if (![key isKindOfClass:[NSString class]]) {
error = YES;
break;
}
value = [tmp objectForKey:key];
if ([value isKindOfClass:[NSString class]]) {
[newDict setObject:value forKey:key];
} else if ([value isKindOfClass:[NSNumber class]]) {
[newDict setObject:[value stringValue] forKey:key];
} else if ([value isKindOfClass:[NSNull class]]) {
[newDict setObject:@"null" forKey:key];
} else if (([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]])
&& [NSJSONSerialization isValidJSONObject:value]) {
[newDict setObject:[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:value
options:kNilOptions
error:nil
]
encoding:NSUTF8StringEncoding]
forKey:key
];
} else {
error = YES;
break;
}
}
if (!error) {
[_content addEntriesFromDictionary:newDict];
} else {
SLSLog(@"Your NSDictionary is not support convert to JSON, all values will not be added, please check your data.");
}
return error;
}
- (void) putContent: (NSString *) key intValue: (int) value {
if ([self checkValue:key]) {
[_content setObject:[NSString stringWithFormat:@"%d", value] forKey:key];
}
}
- (void) putContent: (NSString *) key longValue: (long) value {
if ([self checkValue:key]) {
[_content setObject:[NSString stringWithFormat:@"%ld", value] forKey:key];
}
}
- (void) putContent: (NSString *) key longlongValue: (long long) value {
if ([self checkValue:key]) {
[_content setObject:[NSString stringWithFormat:@"%lld", value] forKey:key];
}
}
- (void) putContent: (NSString *) key floatValue: (float) value {
if ([self checkValue:key]) {
[_content setObject:[NSString stringWithFormat:@"%f", value] forKey:key];
}
}
- (void) putContent: (NSString *) key doubleValue: (double) value {
if ([self checkValue:key]) {
[_content setObject:[NSString stringWithFormat:@"%f", value] forKey:key];
}
}
- (void) putContent: (NSString *) key boolValue: (BOOL) value {
if ([self checkValue:key]) {
[NSNumber numberWithBool:YES];
[_content setObject:(YES == value ? @"YES" : @"NO") forKey:key];
}
}
- (BOOL) putContent: (NSData *) value {
if (!value) {
return NO;
}
if ([value isKindOfClass:[NSNull class]]) {
[self putContent:@"data" value:@"null"];
return YES;
}
NSError *error = nil;
id data = [NSJSONSerialization JSONObjectWithData:value
options:kNilOptions
error:&error
];
if (nil != error) {
NSString *string = [[NSString alloc] initWithData:value encoding:NSUTF8StringEncoding];
[self putContent:@"data" value:string];
return YES;
}
if ([data isKindOfClass:[NSDictionary class]]) {
[self putContents:data];
} else if ([data isKindOfClass:[NSArray class]]) {
[self putContent:@"data" arrayValue:data];
} else {
SLSLog(@"Class %@ not support convert to JSON.", [data class]);
return NO;
}
return YES;
}
- (BOOL) putContent: (NSString *) key dataValue: (NSData *)value {
if ([self checkValue:key] && value && ![value isKindOfClass:[NSNull class]]) {
[_content setObject:[[NSString alloc] initWithData:value
encoding:NSUTF8StringEncoding
]
forKey:key];
return YES;
}
return NO;
}
- (BOOL) putContent: (NSString *) key arrayValue: (NSArray *) value {
if ([self checkValue:key] && value && [NSJSONSerialization isValidJSONObject:value]) {
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:value
options:kNilOptions
error:&error
];
if (nil != error) {
SLSLog(@"error while deserializing NSArray to JSON. error: %@", error.description);
return NO;
}
[_content setObject:[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding
]
forKey:key];
return YES;
}
return NO;
}
- (BOOL) putContent: (NSString *) key dictValue: (NSDictionary *) value {
if ([self checkValue:key] && value && [NSJSONSerialization isValidJSONObject:value]) {
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:value
options:kNilOptions
error:&error
];
if (nil != error) {
SLSLog(@"error while deserializing NSDictionary to JSON. error: %@", error.description);
return NO;
}
[_content setObject:[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding
]
forKey:key];
return YES;
}
return NO;
}
- (NSMutableDictionary *)getContent
{
return _content;
}
- (void)SetTime:(unsigned int) logTime
{
_logTime = logTime;
}
- (unsigned int)getTime
{
return _logTime;
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
</dict>
</plist>
//
// LogProducerClient.m
// AliyunLogProducer
//
// Created by lichao on 2020/9/27.
// Copyright © 2020 lichao. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "LogProducerClient.h"
#import "LogProducerConfig.h"
#import "AliyunLog.h"
#import "TimeUtils.h"
@interface LogProducerClient ()
@end
@implementation LogProducerClient
- (id) initWithLogProducerConfig:(LogProducerConfig *)logProducerConfig
{
return [self initWithLogProducerConfig:logProducerConfig callback:nil];
}
- (id) initWithLogProducerConfig:(LogProducerConfig *)logProducerConfig callback:(on_log_producer_send_done_function)callback
{
return [self initWithLogProducerConfig:logProducerConfig callback:callback userparams:NULL];
}
- (id) initWithLogProducerConfig:(LogProducerConfig *)logProducerConfig callback:(on_log_producer_send_done_function)callback userparams: (NSObject *)params
{
if (self = [super init])
{
self->config = logProducerConfig->config;
self->producer = create_log_producer(logProducerConfig->config, *callback, (nil == params ? nil : (__bridge void *)(params)));
self->client = get_log_producer_client(self->producer, nil);
NSString *endpoint = [logProducerConfig getEndpoint];
NSString *project = [logProducerConfig getProject];
if ([endpoint length] != 0 && [project length] != 0) {
[TimeUtils startUpdateServerTime:endpoint project:project];
}
enable = YES;
}
return self;
}
- (void)DestroyLogProducer
{
if (!enable) {
return;
}
enable = NO;
destroy_log_producer(self->producer);
CFRelease(self->config->user_params);
}
- (LogProducerResult)AddLog:(AliyunLog *) log
{
return [self AddLog:log flush:0];
}
- (LogProducerResult)AddLog:(AliyunLog *) log flush:(int) flush
{
if (!enable || self->client == NULL || log == nil) {
return LogProducerInvalid;
}
NSMutableDictionary *logContents = [log getContent];
int pairCount = (int)[logContents count];
char **keyArray = (char **)malloc(sizeof(char *)*(pairCount));
char **valueArray = (char **)malloc(sizeof(char *)*(pairCount));
int32_t *keyCountArray = (int32_t*)malloc(sizeof(int32_t)*(pairCount));
int32_t *valueCountArray = (int32_t*)malloc(sizeof(int32_t)*(pairCount));
int ids = 0;
for (NSString *key in logContents) {
NSString *string = nil;
id value = logContents[key];
if ([value isKindOfClass:[NSNumber class]]) {
string = [value stringValue];
} else if ([value isKindOfClass: [NSString class]]){
string = value;
} else {
continue;
}
char* keyChar=[self convertToChar:key];
char* valueChar=[self convertToChar:string];
keyArray[ids] = keyChar;
valueArray[ids] = valueChar;
keyCountArray[ids] = (int32_t)strlen(keyChar);
valueCountArray[ids] = (int32_t)strlen(valueChar);
ids = ids + 1;
}
log_producer_result res = log_producer_client_add_log_with_len_time_int32(self->client, [log getTime], pairCount, keyArray, keyCountArray, valueArray, valueCountArray, flush);
for(int i=0;i<pairCount;i++) {
free(keyArray[i]);
free(valueArray[i]);
}
free(keyArray);
free(valueArray);
free(keyCountArray);
free(valueCountArray);
return res;
}
-(char*)convertToChar:(NSString*)strtemp
{
// NSUInteger len = [strtemp lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
// if (len > 1000000) return strdup([strtemp UTF8String]);
// char cStr [len];
// [strtemp getCString:cStr maxLength:len encoding:NSUTF8StringEncoding];
// return strdup(cStr);
NSUInteger len = [strtemp lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
// the limit on stack size will cause crash
// https://github.com/CocoaLumberjack/CocoaLumberjack/issues/38
char* cStr = malloc(sizeof(char) * len);
[strtemp getCString:cStr maxLength:len encoding:NSUTF8StringEncoding];
return cStr;
}
@end
This diff is collapsed.
//
// NSDateFormatter+SLS.m
// AliyunLogProducer
//
// Created by gordon on 2022/6/23.
//
#import "NSDateFormatter+SLS.h"
@interface NSDateFormatter()
@end
@implementation NSDateFormatter (SLS)
+ (instancetype) sharedInstance {
NSMutableDictionary *threadDict = [[NSThread currentThread] threadDictionary];
NSDateFormatter *formater = [threadDict objectForKey:@"sls_date_formater"];
if (!formater) {
@synchronized (self) {
if (!formater) {
formater = [[NSDateFormatter alloc] init];
[formater setTimeZone:[NSTimeZone systemTimeZone]];
[threadDict setObject:formater forKey:@"sls_date_formater"];
}
}
}
return formater;
}
- (NSDate *) fromString: (NSString *) date {
[self setDateFormat:@"YYYY-MM-dd HH:mm:ss:SSS"];
return [self dateFromString:date];
}
- (NSDate *) fromString: (NSString *) date formatter: (NSString *) formatter {
[self setDateFormat:formatter];
return [self dateFromString:date];
}
- (NSDate *) fromStringZ: (NSString *) date {
[self setDateFormat:@"YYYY-MM-dd HH:mm:ss.SSS Z"];
return [self dateFromString:date];
}
- (NSString *) fromDate: (NSDate *) date {
[self setDateFormat:@"YYYY-MM-dd HH:mm:ss:SSS"];
return [self stringFromDate:date];
}
- (NSString *) fromDate: (NSDate *) date formatter: (NSString *) formatter {
[self setDateFormat:formatter];
return [self stringFromDate:date];
}
@end
//
// NSDictionary+SLS.m
// AliyunLogProducer
//
// Created by gordon on 2022/8/16.
//
#import "NSDictionary+SLS.h"
@implementation NSDictionary (SLS)
+ (NSDictionary *) dictionaryWithNSString: (NSString *) string {
if (!string) {
return nil;
}
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error
];
if (nil != error) {
return nil;
}
return dict;
}
@end
//
// NSString+SLS.m
// AliyunLogProducer
//
// Created by gordon on 2022/8/11.
//
#import "NSString+SLS.h"
@implementation NSString (SLS)
- (NSString *) base64Encode {
return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
- (NSString *) base64Decode {
return [[NSString alloc] initWithData:[[NSData alloc] initWithBase64EncodedString:self
options:NSDataBase64DecodingIgnoreUnknownCharacters
]
encoding:NSUTF8StringEncoding
];
}
- (NSDictionary *) toDictionary {
NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error
];
if (error) {
NSLog(@"NSString to NSDictionary error. %@", error);
return [NSDictionary dictionary];
}
return dict;
}
+ (NSString *) stringWithDictionary: (NSDictionary *) dictionary {
if (![NSJSONSerialization isValidJSONObject:dictionary]) {
return [NSString string];
}
NSJSONWritingOptions options = kNilOptions;
if (@available(iOS 11.0, macOS 10.13, watchOS 4.0, tvOS 11.0, *)) {
options = NSJSONWritingSortedKeys;
}
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
options:options
error:&error
];
if (nil != error) {
return [NSString string];
}
return [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding
];
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyTrackingDomains</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyAccessedAPITypes</key>
<array>
<dict>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>35F9.1</string>
</array>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
</dict>
</array>
</dict>
</plist>
//
// HttpHeader.m
// Pods
//
// Created by gordon on 2022/9/21.
//
#import "SLSHttpHeader.h"
#import "SLSUtils.h"
@implementation SLSHttpHeader
+ (NSArray<NSString *> *) getHeaders: (NSArray<NSString *> *) srcHeaders, ... NS_REQUIRES_NIL_TERMINATION {
NSMutableArray<NSString *> *headers = [srcHeaders mutableCopy];
#if SLS_HOST_MAC
NSMutableString *userAgent = [NSMutableString stringWithFormat:@"sls-ios-sdk/%@/macOS", [SLSUtils getSdkVersion]];
#elif SLS_HOST_TV
NSMutableString *userAgent = [NSMutableString stringWithFormat:@"sls-ios-sdk/%@/tvOS", [SLSUtils getSdkVersion]];
#else
NSMutableString *userAgent = [NSMutableString stringWithFormat:@"sls-ios-sdk/%@", [SLSUtils getSdkVersion]];
#endif
[userAgent appendString:@";"];
[headers addObject:@"User-agent"];
va_list args;
NSString *arg;
va_start(args, srcHeaders);
while ((arg = va_arg(args, NSString*))) {
[userAgent appendString:arg];
[userAgent appendString:@";"];
}
va_end(args);
[headers addObject:[userAgent substringToIndex:userAgent.length-1]];
return headers;
}
@end
//
// SLSURLSession.h
// AliyunLogProducer
//
// Created by gordon on 2022/8/16.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface SLSURLSession : NSObject
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request
returningResponse:(NSURLResponse *_Nullable*_Nullable)response
error:(NSError **)error;
@end
NS_ASSUME_NONNULL_END
//
// SLSURLSession.m
// AliyunLogProducer
//
// Created by gordon on 2022/8/16.
//
#import "SLSURLSession.h"
@implementation SLSURLSession
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request
returningResponse:(NSURLResponse *_Nullable*_Nullable)response
error:(NSError **)error {
// ref: https://stackoverflow.com/a/37829399/1760982
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
NSError __block *err = NULL;
NSData __block *data;
NSURLResponse __block *resp;
[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData* _data, NSURLResponse* _response, NSError* _error) {
resp = _response;
err = _error;
data = _data;
dispatch_group_leave(group);
}] resume];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
if (response)
{
*response = resp;
}
if (error)
{
*error = err;
}
return data;
}
@end
//
// SLSUtils.m
// Pods
//
// Created by gordon on 2022/9/21.
//
#import "SLSUtils.h"
#import "AliyunLogProducer.h"
@implementation SLSUtils
+ (NSString *) getSdkVersion {
return SLS_SDK_VERSION;
}
@end
//
// TimeUtils.m
// AliyunLogProducer
//
// Created by gordon on 2021/6/8.
// Copyright © 2021 lichao. All rights reserved.
//
#import "TimeUtils.h"
#import "LogProducerConfig.h"
#import <sys/sysctl.h>
#import "NSDateFormatter+SLS.h"
@interface TimeUtils ()
+(NSTimeInterval) elapsedRealtime;
@end
static NSInteger serverTime = 0;
static NSTimeInterval elapsedRealtime = 0;
@implementation TimeUtils
+(void) startUpdateServerTime: (NSString *)endpoint project:(nonnull NSString *)project
{
if (!endpoint || endpoint.length <=0 ) {
return;
}
NSURL *url = [NSURL URLWithString:endpoint];
if (nil == url || !url.host || url.host.length <= 0) {
return;
}
NSString *urlString = [NSString stringWithFormat:@"https://%@.%@/servertime", project, url.host];
// NSString *url = @"https://cn-shanghai-staging-share.sls.aliyuncs.com/servertime";
// NSString *urlString = [NSString stringWithUTF8String:[url UTF8String]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod: @"GET"];
[request setURL:[NSURL URLWithString:urlString]];
[request addValue:@"0.6.0" forHTTPHeaderField:@"x-log-apiversion"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (response != nil) {
NSHTTPURLResponse *httpResponse = response;
NSDictionary *fields = [httpResponse allHeaderFields];
NSString *timeVal = fields[@"x-log-time"];
if ([timeVal length] != 0) {
NSInteger serverTime = [timeVal integerValue];
if (serverTime > 1500000000 && serverTime < 4294967294) {
[TimeUtils updateServerTime:serverTime];
}
}
}
}];
}
+(void) updateServerTime: (NSInteger) timeInMillis
{
serverTime = timeInMillis;
elapsedRealtime = [self elapsedRealtime];
}
+(NSInteger) getTimeInMilliis
{
if( 0L == elapsedRealtime) {
NSInteger time = [[NSDate date] timeIntervalSince1970];
return time;
}
NSInteger delta = [self elapsedRealtime] - elapsedRealtime;
return serverTime + delta;
}
+(void) fixTime: (AliyunLog *)log
{
if(!log) {
return;
}
NSMutableDictionary *dictionary = [log getContent];
if (!dictionary || [dictionary count] == 0) {
return;
}
if (![dictionary objectForKey:@"local_timestamp"]) {
return;
}
NSString *local_timestamp = [NSString stringWithString:[[log getContent] objectForKey:@"local_timestamp"]];
if ([local_timestamp length] < 10) {
return;
}
NSLog(@"log.getTime: %d", [log getTime]);
NSDate *date = [NSDate date];
NSString *timestamp = [local_timestamp substringWithRange:NSMakeRange(0, 10)];
NSString *timestampMillisPart = [[NSString stringWithFormat:@"%.0f", [date timeIntervalSince1970] * 1000] substringFromIndex:10];
local_timestamp = [timestamp stringByAppendingString:timestampMillisPart];
NSDateFormatter *dateFormatter = [NSDateFormatter sharedInstance];
date = [NSDate dateWithTimeIntervalSince1970:[local_timestamp doubleValue] / 1000];
NSString *local_time = [dateFormatter fromDate:date];
[log PutContent:@"local_timestamp_fixed" value:local_timestamp];
[log PutContent:@"local_time_fixed" value:local_time];
}
+ (NSTimeInterval)elapsedRealtime {
struct timeval boottime;
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
size_t size = sizeof(boottime);
struct timeval now;
struct timezone tz;
gettimeofday(&now, &tz);
double uptime = -1;
if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0)
{
uptime = now.tv_sec - boottime.tv_sec;
uptime += (double)(now.tv_usec - boottime.tv_usec) / 1000000.0;
return uptime;
}
return [[NSProcessInfo processInfo] systemUptime];
}
@end
//
// AliyunLog.h
// AliyunLogProducer
//
// Created by lichao on 2020/9/27.
// Copyright © 2020 lichao. All rights reserved.
//
#ifndef AliyunLog_h
#define AliyunLog_h
#endif /* AliyunLog_h */
@interface AliyunLog : NSObject
+ (instancetype) log;
/// Put string value to log with NSString key. This method will be removed in the future.
/// @param key NSString
/// @param value BOOL
/// swift compile error, ref: https://stackoverflow.com/questions/52557738/objective-c-framework-used-in-swift-ambiguous-use-of-method-error
- (void) PutContent: (NSString *) key value: (NSString *) value __attribute__((deprecated("use method putContent:value:"))) NS_SWIFT_UNAVAILABLE("deprecated method not available in Swift");
/// Put string value to log with NSString key.
/// @param key NSString
/// @param value BOOL
- (void) putContent: (NSString *) key value: (NSString *) value;
/// Put int value to log with NSString key.
/// @param key NSString
/// @param value BOOL
- (void) putContent: (NSString *) key intValue: (int) value;
/// Put long value to log with NSString key.
/// @param key NSString
/// @param value BOOL
- (void) putContent: (NSString *) key longValue: (long) value;
/// Put long long value to log with NSString key.
/// @param key NSString
/// @param value BOOL
- (void) putContent: (NSString *) key longlongValue: (long long) value;
/// Put float value to log with NSString key.
/// @param key NSString
/// @param value BOOL
- (void) putContent: (NSString *) key floatValue: (float) value;
/// Put double value to log with NSString key.
/// @param key NSString
/// @param value BOOL
- (void) putContent: (NSString *) key doubleValue: (double) value;
/// Put bool value to log with NSString key.
/// @param key NSString
/// @param value BOOL
- (void) putContent: (NSString *) key boolValue: (BOOL) value;
/// Put NSData contents to log. All K-V from this dictionaray will be added to the root node.
/// @param value NSData, must be able to convert to JSON, if not will return NO.
/// @return BOOL YES, put success; NO, put fails.
- (BOOL) putContent: (NSData *) value;
/// Put NSData with key to log. All K-V from this array will be added to the node with the given specified key.
/// @param key NSString
/// @param value NSData, must be able to convert to JSON, if not will return NO.
- (BOOL) putContent: (NSString *) key dataValue: (NSData *) value;
/// Put NSArray with key to log. All K-V from this array will be added to the node with the given specified key.
/// @param key NSString
/// @param value NSArray, must be able to convert to JSON, if not will return NO.
- (BOOL) putContent: (NSString *) key arrayValue: (NSArray *) value;
/// Put NSDictionaray with key to log. All K-V from this dictionaray will be added to the node with the given specified key.
/// @param key NSString
/// @param value NSDictionaray, must be able to convert to JSON, if not will return NO.
- (BOOL) putContent: (NSString *) key dictValue: (NSDictionary *) value;
/// Put NSDictionaray contents to log. All K-V from this dictionaray will be added to the root node.
/// @param dict NSDictionaray, must be able to convert to JSON, if not will return NO.
/// @return BOOL YES, put success; NO, put fails.
- (BOOL) putContents: (NSDictionary *) dict;
- (NSMutableDictionary *) getContent;
/// Should not SetTime directly. This method will be removed in the future.
- (void)SetTime:(unsigned int) logTime;
- (unsigned int) getTime;
@end
//
// AliyunLogProducer.h
// AliyunLogProducer
//
// Created by lichao on 2020/9/27.
// Copyright © 2020 lichao. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for AliyunLogProducer.
FOUNDATION_EXPORT double AliyunLogProducerVersionNumber;
//! Project version string for AliyunLogProducer.
FOUNDATION_EXPORT const unsigned char AliyunLogProducerVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <AliyunLogProducer/PublicHeader.h>
#import "SLSProducer.h"
//// AliyunLogCore
//#if __has_include("AliyunLogCore/AliyunLogCore.h")
//#import "AliyunLogCore/AliyunLogCore.h"
//#elif __has_include("AliyunLogCore.h")
//#import "AliyunLogCore.h"
//#endif
//// AliyunLogCrashReporter
//#if __has_include("AliyunLogCrashReporter/AliyunLogCrashReporter.h")
//#import "AliyunLogCrashReporter/AliyunLogCrashReporter.h"
//#elif __has_include("AliyunLogCrashReporter.h")
//#import "AliyunLogCrashReporter.h"
//#endif
//
//// AliyunLogNetworkDiagnosis
//#if __has_include("AliyunLogNetworkDiagnosis/AliyunLogNetworkDiagnosis.h")
//#import "AliyunLogNetworkDiagnosis/AliyunLogNetworkDiagnosis.h"
//#elif __has_include("AliyunLogNetworkDiagnosis.h")
//#import "AliyunLogNetworkDiagnosis.h"
//#endif
//
//// AliyunLogTrace
//#if __has_include("AliyunLogTrace/AliyunLogTrace.h")
//#import "AliyunLogTrace/AliyunLogTrace.h"
//#elif __has_include("AliyunLogTrace.h")
//#import "AliyunLogTrace.h"
//#endif
//
//// Swift
//#if __has_include("AliyunLogProducer-Swift.h")
//#import "AliyunLogProducer-Swift.h"
//#endif
//
//// AliyunLogURLSession
//#if __has_include("AliyunLogURLSession/AliyunLogURLSession-Swift.h")
//#import "AliyunLogURLSession/AliyunLogURLSession-Swift.h"
//#endif
//
// LogProducerClient.h
// AliyunLogProducer
//
// Created by lichao on 2020/9/27.
// Copyright © 2020 lichao. All rights reserved.
//
#ifndef LogProducerClient_h
#define LogProducerClient_h
#endif /* LogProducerClient_h */
#import "log_producer_client.h"
#import "LogProducerConfig.h"
#import "AliyunLog.h"
typedef void (^AddLogInterceptor)(AliyunLog *log);
@interface LogProducerClient : NSObject
{
@private log_producer* producer;
@private log_producer_config* config;
@private log_producer_client* client;
@private BOOL _enableTrack;
@private BOOL enable;
}
typedef NS_ENUM(NSInteger, LogProducerResult) {
LogProducerOK = 0,
LogProducerInvalid,
LogProducerWriteError,
LogProducerDropError,
LogProducerSendNetworkError,
LogProducerSendQuotaError,
LogProducerSendUnauthorized,
LogProducerSendServerError,
LogProducerSendDiscardError,
LogProducerSendTimeError,
LogProducerSendExitBufferdF,
LogProducerParametersInvalid,
LogProducerPERSISTENT_Error = 99
};
- (id) initWithLogProducerConfig:(LogProducerConfig *)logProducerConfig;
- (id) initWithLogProducerConfig:(LogProducerConfig *)logProducerConfig callback:(on_log_producer_send_done_function)callback;
- (id) initWithLogProducerConfig:(LogProducerConfig *)logProducerConfig callback:(on_log_producer_send_done_function)callback userparams: (NSObject *)params;
- (void)DestroyLogProducer;
- (LogProducerResult)AddLog:(AliyunLog *) log;
- (LogProducerResult)AddLog:(AliyunLog *) log flush:(int) flush;
@end
//
// LogProducerConfig.h
// AliyunLogProducer
//
// Created by lichao on 2020/9/27.
// Copyright © 2020 lichao. All rights reserved.
//
#ifndef LogProducerConfig_h
#define LogProducerConfig_h
#endif /* LogProducerConfig_h */
#import "log_producer_config.h"
#import "log_http_interface.h"
typedef NSArray<NSString *> * (^SLSHttpHeaderInjector) (NSArray<NSString *> *srcHeaders);
@interface LogProducerConfig : NSObject
{
@package log_producer_config* config;
@private NSString *endpoint;
@private NSString *project;
@private NSString *logstore;
}
- (id) initWithEndpoint:(NSString *) endpoint project:(NSString *)project logstore:(NSString *)logstore accessKeyID:(NSString *)accessKeyID accessKeySecret:(NSString *)accessKeySecret;
- (id) initWithEndpoint:(NSString *) endpoint project:(NSString *)project logstore:(NSString *)logstore accessKeyID:(NSString *)accessKeyID accessKeySecret:(NSString *)accessKeySecret securityToken:(NSString *)securityToken;
- (id) initWithEndpoint:(NSString *) endpoint project:(NSString *)project logstore:(NSString *)logstore;
- (void)SetTopic:(NSString *) topic;
- (void)SetSource:(NSString *) source;
- (void)AddTag:(NSString *) key value:(NSString *)value;
- (void)SetPacketLogBytes:(int) num;
- (void)SetPacketLogCount:(int) num;
- (void)SetPacketTimeout:(int) num;
- (void)SetMaxBufferLimit:(int) num;
- (void)SetSendThreadCount:(int) num;
- (void)SetPersistent:(int) num;
- (void)SetPersistentFilePath:(NSString *) path;
- (void)SetPersistentForceFlush:(int) num;
- (void)SetPersistentMaxFileCount:(int) num;
- (void)SetPersistentMaxFileSize:(int) num;
- (void)SetPersistentMaxLogCount:(int) num;
- (void)SetUsingHttp:(int) num;
- (void)SetNetInterface:(NSString *) netInterface;
- (void)SetConnectTimeoutSec:(int) num;
- (void)SetSendTimeoutSec:(int) num;
- (void)SetDestroyFlusherWaitSec:(int) num;
- (void)SetDestroySenderWaitSec:(int) num;
- (void)SetCompressType:(int) num;
- (void)SetNtpTimeOffset:(int) num;
- (void)SetMaxLogDelayTime:(int) num;
- (void)SetDropDelayLog:(int) num;
- (void)SetDropUnauthorizedLog:(int) num;
- (void)SetGetTimeUnixFunc:(unsigned int (*)()) f;
- (int)IsValid;
- (int)IsEnabled;
- (void) setEndpoint: (NSString *)endpoint;
- (NSString *)getEndpoint;
- (void) setProject: (NSString *)project;
- (NSString *)getProject;
- (void) setLogstore: (NSString *)logstore;
- (NSString *) getLogStore;
- (void) ResetSecurityToken:(NSString *) accessKeyID accessKeySecret:(NSString *)accessKeySecret securityToken:(NSString *)securityToken;
- (void) setAccessKeyId: (NSString *)accessKeyId;
- (void) setAccessKeySecret: (NSString *) accessKeySecret;
- (void) setUseWebtracking: (BOOL) enable;
- (void) setHttpHeaderInjector: (SLSHttpHeaderInjector) injector;
+ (void) Debug;
@end
//
// NSDateFormatter+SLS.h
// AliyunLogProducer
//
// Created by gordon on 2022/6/23.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSDateFormatter (SLS)
+ (instancetype) sharedInstance;
- (NSDate *) fromString: (NSString *) date;
- (NSDate *) fromString: (NSString *) date formatter: (NSString *) formatter;
- (NSDate *) fromStringZ: (NSString *) date;
- (NSString *) fromDate: (NSDate *) date;
- (NSString *) fromDate: (NSDate *) date formatter: (NSString *) formatter;
@end
NS_ASSUME_NONNULL_END
//
// NSDictionary+SLS.h
// AliyunLogProducer
//
// Created by gordon on 2022/8/16.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSDictionary (SLS)
+ (NSDictionary *) dictionaryWithNSString: (NSString *) string;
@end
NS_ASSUME_NONNULL_END
//
// NSString+SLS.h
// AliyunLogProducer
//
// Created by gordon on 2022/8/11.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSString (SLS)
/**
* Encode string with base64.
*/
- (NSString *) base64Encode;
/**
* Decode string with base64.
*/
- (NSString *) base64Decode;
/**
* String to dictionary.
*/
- (NSDictionary *) toDictionary;
/**
* String with dictionary.
*/
+ (NSString *) stringWithDictionary: (NSDictionary *) dictionary;
@end
NS_ASSUME_NONNULL_END
//
// HttpHeader.h
// Pods
//
// Created by gordon on 2022/9/21.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface SLSHttpHeader : NSObject
+ (NSArray<NSString *> *) getHeaders: (NSArray<NSString *> *) srcHeaders, ... NS_REQUIRES_NIL_TERMINATION;
@end
NS_ASSUME_NONNULL_END
//
// SLSProducer.h
// AliyunLogProducer
//
// Created by gordon on 2023/1/18.
// Copyright © 2023 com.aysls.ios. All rights reserved.
//
#import <Foundation/Foundation.h>
#ifndef AliyunlogCommon_h
#define AliyunlogCommon_h
//! Xcode 13 has a new option called "Manage Version and Build Number" which is ticked by default.
//! If left checked, Xcode will automatically set your app's version number which (rather counter-intuitively), will also apply to all included frameworks
//! https://stackoverflow.com/a/31418789/1760982
#define SLS_SDK_VERSION @"3.1.19"
#define SLSLog(fmt, ...) NSLog((@"[SLSiOS] %s " fmt), __FUNCTION__, ##__VA_ARGS__);
#ifdef DEBUG
#define SLSLogV(fmt, ...) NSLog((@"[SLSiOS] %s:%d: " fmt), __FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define SLSLogV(...);
#endif
#endif /* AliyunlogCommon_h */
#import "LogProducerClient.h"
#import "LogProducerConfig.h"
#import "AliyunLog.h"
#import "NSDateFormatter+SLS.h"
#import "NSDictionary+SLS.h"
#import "NSString+SLS.h"
#import "SLSHttpHeader.h"
#import "SLSSystemCapabilities.h"
#import "SLSUtils.h"
#import "TimeUtils.h"
//
// SLSSystemCapabilities.h
// Pods
//
// Created by gordon on 2022/3/9.
//
#ifndef SLSSystemCapabilities_h
#define SLSSystemCapabilities_h
#ifdef __APPLE__
#include <TargetConditionals.h>
#define SLS_HOST_APPLE 1
#endif
#define SLS_HOST_IOS (SLS_HOST_APPLE && TARGET_OS_IOS)
#define SLS_HOST_TV (SLS_HOST_APPLE && TARGET_OS_TV)
#define SLS_HOST_WATCH (SLS_HOST_APPLE && TARGET_OS_WATCH)
#define SLS_HOST_MAC (SLS_HOST_APPLE && TARGET_OS_MAC && !(TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH)) || (SLS_HOST_APPLE && TARGET_OS_MACCATALYST)
#if SLS_HOST_IOS || SLS_HOST_TV || SLS_HOST_WATCH
#define SLS_HAS_UIKIT 1
#else
#define SLS_HAS_UIKIT 0
#endif
#if SLS_HOST_IOS && !TARGET_OS_MACCATALYST
#define SLS_HAS_CORE_TELEPHONY 1
#else
#define SLS_HAS_CORE_TELEPHONY 0
#endif
#endif /* SLSSystemCapabilities_h */
//
// SLSUtils.h
// Pods
//
// Created by gordon on 2022/9/21.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface SLSUtils : NSObject
+ (NSString *) getSdkVersion;
@end
NS_ASSUME_NONNULL_END
//
// TimeUtils.h
// AliyunLogProducer
//
// Created by gordon on 2021/6/8.
// Copyright © 2021 lichao. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AliyunLog.h"
NS_ASSUME_NONNULL_BEGIN
@interface TimeUtils : NSObject
+(void) startUpdateServerTime: (NSString *)endpoint project: (NSString *)project;
+(void) updateServerTime: (NSInteger) timeInMillis;
+(NSInteger) getTimeInMilliis;
+(void) fixTime: (AliyunLog *)log;
@end
NS_ASSUME_NONNULL_END
#ifndef LIBAOS_LOG_H
#define LIBAOS_LOG_H
#include <string.h>
#ifdef __cplusplus
extern "C"
{
#endif
typedef enum {
AOS_LOG_OFF = 1,
AOS_LOG_FATAL,
AOS_LOG_ERROR,
AOS_LOG_WARN,
AOS_LOG_INFO,
AOS_LOG_DEBUG,
AOS_LOG_TRACE,
AOS_LOG_ALL
} aos_log_level_e;
extern aos_log_level_e aos_log_level;
void aos_log_format(int level,
const char *file,
int line,
const char *function,
const char *fmt, ...);
void aos_print_log_android(int level, char *log);
void aos_log_set_level(aos_log_level_e level);
#ifdef __ANDROID__
#define print_log(level, log) aos_print_log_android(level, log)
#else
#define print_log(level, log) puts(log)
#endif
#ifdef WIN32
#define __FL_NME__ (strchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#define aos_fatal_log(format, ...) if(aos_log_level>=AOS_LOG_FATAL) \
aos_log_format(AOS_LOG_FATAL, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_error_log(format, ...) if(aos_log_level>=AOS_LOG_ERROR) \
aos_log_format(AOS_LOG_ERROR, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_warn_log(format, ...) if(aos_log_level>=AOS_LOG_WARN) \
aos_log_format(AOS_LOG_WARN, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_info_log(format, ...) if(aos_log_level>=AOS_LOG_INFO) \
aos_log_format(AOS_LOG_INFO, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_debug_log(format, ...) if(aos_log_level>=AOS_LOG_DEBUG) \
aos_log_format(AOS_LOG_DEBUG, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_trace_log(format, ...) if(aos_log_level>=AOS_LOG_TRACE) \
aos_log_format(AOS_LOG_TRACE, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#else
#define __FL_NME__ (strchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#define aos_fatal_log(format, args...) if(aos_log_level>=AOS_LOG_FATAL) \
aos_log_format(AOS_LOG_FATAL, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_error_log(format, args...) if(aos_log_level>=AOS_LOG_ERROR) \
aos_log_format(AOS_LOG_ERROR, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_warn_log(format, args...) if(aos_log_level>=AOS_LOG_WARN) \
aos_log_format(AOS_LOG_WARN, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_info_log(format, args...) if(aos_log_level>=AOS_LOG_INFO) \
aos_log_format(AOS_LOG_INFO, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_debug_log(format, args...) if(aos_log_level>=AOS_LOG_DEBUG) \
aos_log_format(AOS_LOG_DEBUG, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_trace_log(format, args...) if(aos_log_level>=AOS_LOG_TRACE) \
aos_log_format(AOS_LOG_TRACE, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#endif
#ifdef __cplusplus
}
#endif
#endif
#ifndef LIBLOG_DEFINE_H
#define LIBLOG_DEFINE_H
#ifdef WIN32
#define LOG_EXPORT _declspec(dllexport)
#else
#define LOG_EXPORT
#endif
#ifdef __cplusplus
# define LOG_CPP_START extern "C" {
# define LOG_CPP_END }
#else
# define LOG_CPP_START
# define LOG_CPP_END
#endif
typedef int log_status_t;
struct _post_log_result
{
int statusCode;
char * errorMessage;
char * requestID;
};
typedef struct _post_log_result post_log_result;
#endif
#ifndef SLS_HTTP_INTERFACE_H
#define SLS_HTTP_INTERFACE_H
#include "log_define.h"
#include "log_producer_config.h"
LOG_CPP_START
/**
* register http post function for sending logs
* @param f function ptr to send http post request
*/
__attribute__ ((visibility("default")))
void log_set_http_post_func(int (*f)(const char *url,
char **header_array,
int header_count,
const void *data,
int data_len,
post_log_result *http_response));
/**
* register get time function for get log time
* @param f function ptr to get time unix seconds, like time(NULL)
*/
__attribute__ ((visibility("default")))
void log_set_get_time_unix_func(unsigned int (*f)());
__attribute__ ((visibility("default")))
void log_set_http_header_inject_func(void (*f) (log_producer_config *config,
char **src_headers,
int src_count,
char **dest_headers,
int *dest_count)
);
__attribute__ ((visibility("default")))
void log_set_http_header_release_inject_func(void (*f) (log_producer_config *config,
char **dest_headers,
int dest_count)
);
LOG_CPP_END
#endif//SLS_HTTP_INTERFACE_H
#ifndef LOG_INNER_INCLUDE_H
#define LOG_INNER_INCLUDE_H
//操作系统头文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <errno.h>
#ifdef WIN32
#define inline __inline
#include <winsock2.h>
#include <sys/timeb.h>
#include <windows.h>
#include <process.h>
#include <assert.h>
typedef int socklen_t;
#elif defined(_VXWORKS)
#include <vxworks.h>
#include <netdb.h>
#include <string.h>
#include <ctype.h>
#include <types.h>
#include <sockLib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/times.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <hostLib.h>
#include <ticklib.h>
#include <drv/timer/ppcDecTimer.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <tipc/tipc.h>
#include <taskLib.h>
#include <selectLib.h>//for vx6
#include <ioLib.h>
#include <ioctl.h>
#else
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <semaphore.h>
#include <assert.h>
#include <sys/time.h>
#include <stdint.h>
#endif
#if defined WIN32 || defined _VXWORKS
typedef unsigned char u_char;
typedef unsigned char u_int8;
typedef unsigned short u_int16;
typedef unsigned int u_int32;
typedef unsigned __int64 u_int64;
typedef signed char int8;
typedef signed short int16;
typedef signed int int32;
typedef signed __int64 int64;
#elif defined __linux__
typedef unsigned char u_char;
typedef unsigned char u_int8;
typedef unsigned short u_int16;
typedef unsigned int u_int32;
typedef unsigned long long u_int64;
typedef signed char int8;
typedef signed short int16;
typedef signed int int32;
typedef long long int64;
typedef int SOCKET;
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#define __in // 参数输入
#define __out // 参数输出
#define closesocket close
#define stricmp strcasecmp
typedef int BOOL;
#define TRUE 1
#define FALSE 0
#define Sleep(param) usleep(1000*(param))
#define strcpy_s(a, b, c) strcpy(a, c)
#define sprintf_s(a, b, c) sprintf(a, c)
#define strncpy_s(a, b, c, d) strncpy(a, c, d)
#define vsprintf_s(a, b, c, d) vsprintf(a, c, d)
#define _strdup strdup
#define _stricmp stricmp
#endif
#endif //LOG_INNER_INCLUDE_H
//
// Created by ZhangCheng on 20/11/2017.
//
#ifndef LOG_C_SDK_LOG_PRODUCER_CLIENT_H
#define LOG_C_SDK_LOG_PRODUCER_CLIENT_H
#include "log_define.h"
#include "log_producer_config.h"
LOG_CPP_START
/**
* log producer client
*/
typedef struct _log_producer_client
{
volatile int32_t valid_flag;
int32_t log_level;
void * private_data;
}log_producer_client;
typedef struct _log_producer log_producer;
/**
* init log producer environment
* @note should been called before create any log producer client
* @note no multi thread safe
* @return OK if success, others the error code
*/
LOG_EXPORT log_producer_result log_producer_env_init();
/**
* destroy log producer environment
* @note should been called after all log producer clients destroyed
* @note no multi thread safe
*/
LOG_EXPORT void log_producer_env_destroy();
/**
* create log producer with a producer config
* @param config log_producer_config
* @param send_done_function this function will be called when send done(can be ok or fail), set to NULL if you don't care about it
* @param user_param this param will send back in send_done_function
* @return producer client ptr, NULL if create fail
*/
LOG_EXPORT log_producer * create_log_producer(log_producer_config * config, on_log_producer_send_done_function send_done_function, void *user_param);
/**
* destroy log producer
* @param producer
* @note no multi thread safe
*/
LOG_EXPORT void destroy_log_producer(log_producer * producer);
/**
* get client from producer
* @param producer
* @param config_name useless now, set NULL
* @return the specific producer client, root client if config_name is NULL or no specific config,
*/
LOG_EXPORT log_producer_client * get_log_producer_client(log_producer * producer, const char * config_name);
/**
* force send data when network recover
* @param client
*/
LOG_EXPORT void log_producer_client_network_recover(log_producer_client * client);
/**
* add log to producer, this may return LOG_PRODUCER_DROP_ERROR if buffer is full.
* if you care about this log very much, retry when return LOG_PRODUCER_DROP_ERROR.
*
* @example log_producer_client_add_log(client, 4, "key_1", "value_1", "key_2", "value_2")
* @note log param ... must be const char * or char * with '\0' ended
* @note multi thread safe
* @param client
* @param kv_count key value count
* @param ... log params : key, value pairs, must be const char * or char *
* @return ok if success, LOG_PRODUCER_DROP_ERROR if buffer is full, LOG_PRODUCER_INVALID if client is destroyed.
*/
LOG_EXPORT log_producer_result log_producer_client_add_log(log_producer_client * client, int32_t kv_count, ...);
/**
* add log to producer, this may return LOG_PRODUCER_DROP_ERROR if buffer is full.
* if you care about this log very much, retry when return LOG_PRODUCER_DROP_ERROR.
*
* @param client
* @param pair_count key value pair count
* @note pair_count not kv_count
* @param keys the key array
* @param key_lens the key len array
* @param values the value array
* @param value_lens the value len array
* @param flush if this log info need to send right, 1 mean flush and 0 means NO
* @return ok if success, LOG_PRODUCER_DROP_ERROR if buffer is full, LOG_PRODUCER_INVALID if client is destroyed, LOG_PRODUCER_PERSISTENT_ERROR is save binlog failed.
*/
LOG_EXPORT log_producer_result log_producer_client_add_log_with_len(log_producer_client * client, int32_t pair_count, char ** keys, size_t * key_lens, char ** values, size_t * value_lens, int flush);
/**
* @note same with log_producer_client_add_log_with_len but use int32_t as length
* add log to producer, this may return LOG_PRODUCER_DROP_ERROR if buffer is full.
* if you care about this log very much, retry when return LOG_PRODUCER_DROP_ERROR.
*
* @param client
* @param pair_count key value pair count
* @note pair_count not kv_count
* @param keys the key array
* @param key_lens the key len array
* @param values the value array
* @param value_lens the value len array
* @param flush if this log info need to send right, 1 mean flush and 0 means NO
* @return ok if success, LOG_PRODUCER_DROP_ERROR if buffer is full, LOG_PRODUCER_INVALID if client is destroyed, LOG_PRODUCER_PERSISTENT_ERROR is save binlog failed.
*/
LOG_EXPORT log_producer_result log_producer_client_add_log_with_len_int32(log_producer_client * client, int32_t pair_count, char ** keys, int32_t * key_lens, char ** values, int32_t * value_lens, int flush);
/**
* @note same with log_producer_client_add_log_with_len_int32 but set time
* add log to producer, this may return LOG_PRODUCER_DROP_ERROR if buffer is full.
* if you care about this log very much, retry when return LOG_PRODUCER_DROP_ERROR.
*
* @param client
* @param pair_count key value pair count
* @note pair_count not kv_count
* @param keys the key array
* @param key_lens the key len array
* @param values the value array
* @param value_lens the value len array
* @param flush if this log info need to send right, 1 mean flush and 0 means NO
* @return ok if success, LOG_PRODUCER_DROP_ERROR if buffer is full, LOG_PRODUCER_INVALID if client is destroyed, LOG_PRODUCER_PERSISTENT_ERROR is save binlog failed.
*/
LOG_EXPORT log_producer_result log_producer_client_add_log_with_len_time_int32(log_producer_client * client, uint32_t time_sec, int32_t pair_count, char ** keys, int32_t * key_lens, char ** values, int32_t * value_lens, int flush);
/**
* add raw pb log buffer
* @param client
* @param logBuf
* @param logSize
* @param flush
* @return same as log_producer_client_add_log_with_len
*/
LOG_EXPORT log_producer_result log_producer_client_add_log_raw(log_producer_client * client,
char * logBuf,
size_t logSize,
int flush);
/**
* add raw log with string buffer
* @param client
* @param logTime
* @param logItemCount
* @param logItemsBuf
* @param logItemsSize
* @param flush
* @return same as log_producer_client_add_log_with_len
*/
LOG_EXPORT log_producer_result log_producer_client_add_log_with_array(log_producer_client * client,
uint32_t logTime,
size_t logItemCount,
const char * logItemsBuf,
const uint32_t * logItemsSize,
int flush);
/**
* add raw log buffer to client, this function is used to send buffers which can not send out when producer has destroyed
* @param client
* @param log_bytes
* @param compressed_bytes
* @param raw_buffer
* @return ok if success, LOG_PRODUCER_DROP_ERROR if buffer is full, LOG_PRODUCER_INVALID if client is destroyed, LOG_PRODUCER_PERSISTENT_ERROR is save binlog failed.
*/
LOG_EXPORT log_producer_result log_producer_client_add_raw_log_buffer(log_producer_client * client, size_t log_bytes, size_t compressed_bytes, const unsigned char * raw_buffer);
LOG_CPP_END
#endif //LOG_C_SDK_LOG_PRODUCER_CLIENT_H
//
// Created by ZhangCheng on 21/11/2017.
//
#ifndef LOG_C_SDK_LOG_PRODUCER_COMMON_H_H
#define LOG_C_SDK_LOG_PRODUCER_COMMON_H_H
#include "log_define.h"
#include <stdint.h>
#include <stddef.h>
LOG_CPP_START
/**
* log producer result for all operation
*/
typedef int log_producer_result;
/**
* callback function for producer client
* @param result send result
* @param log_bytes log group packaged bytes
* @param compressed_bytes lz4 compressed bytes
* @param error_message if send result is not ok, error message is set. must check if is NULL when use it
* @param raw_buffer lz4 buffer
* @note you can only read raw_buffer, but can't modify or free it
*/
typedef void(*on_log_producer_send_done_function)(const char * config_name, log_producer_result result, size_t log_bytes, size_t compressed_bytes, const char * req_id, const char * error_message, const unsigned char * raw_buffer, void *user_param);
typedef void(*on_log_producer_send_done_uuid_function)(const char * config_name,
log_producer_result result,
size_t log_bytes,
size_t compressed_bytes,
const char * req_id,
const char * error_message,
const unsigned char * raw_buffer,
void *user_param,
int64_t startId,
int64_t endId);
extern log_producer_result LOG_PRODUCER_OK;
extern log_producer_result LOG_PRODUCER_INVALID;
extern log_producer_result LOG_PRODUCER_WRITE_ERROR;
extern log_producer_result LOG_PRODUCER_DROP_ERROR;
extern log_producer_result LOG_PRODUCER_SEND_NETWORK_ERROR;
extern log_producer_result LOG_PRODUCER_SEND_QUOTA_ERROR;
extern log_producer_result LOG_PRODUCER_SEND_UNAUTHORIZED;
extern log_producer_result LOG_PRODUCER_SEND_SERVER_ERROR;
extern log_producer_result LOG_PRODUCER_SEND_DISCARD_ERROR;
extern log_producer_result LOG_PRODUCER_SEND_TIME_ERROR;
extern log_producer_result LOG_PRODUCER_SEND_EXIT_BUFFERED;
extern log_producer_result LOG_PRODUCER_PARAMETERS_INVALID;
extern log_producer_result LOG_PRODUCER_PERSISTENT_ERROR;
/**
* check if rst if ok
* @param rst
* @return 1 if ok, 0 not ok
*/
LOG_EXPORT int is_log_producer_result_ok(log_producer_result rst);
LOG_CPP_END
#endif //LOG_C_SDK_LOG_PRODUCER_COMMON_H_H
#include "inner_log.h"
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
aos_log_level_e aos_log_level = AOS_LOG_WARN;
static const char * _aos_log_level_str[] = {
"NONE",
"NONE",
"FATAL",
"ERROR",
"WARN",
"INFO",
"DEBUG",
"TRACE",
"NONE"
};
void aos_log_set_level(aos_log_level_e level)
{
aos_log_level = level;
}
void aos_log_format(int level,
const char *file,
int line,
const char *function,
const char *fmt, ...)
{
va_list args;
char buffer[1024];
int maxLen = 1020;
// @note return value maybe < 0 || > maxLen
int len = snprintf(buffer, maxLen, "[%s] [%s][%s:%d] ",
_aos_log_level_str[level],
file, function, line);
// should never happen
if (len < 0 || len > maxLen) {
print_log(AOS_LOG_ERROR, "[aos_log_format] error log fmt\n");
return;
}
va_start(args, fmt);
// @note return value maybe < 0 || > maxLen
int rst = vsnprintf(buffer + len, maxLen - len, fmt, args);
va_end(args);
if (rst < 0) {
print_log(AOS_LOG_ERROR, "[aos_log_format] error log fmt\n");
return;
}
if (rst > maxLen - len) {
rst = maxLen - len;
}
len += rst;
while (len > 0 && buffer[len -1] == '\n')
{
len--;
}
buffer[len++] = '\n';
buffer[len] = '\0';
print_log(level, buffer);
}
\ No newline at end of file
#ifndef LIBAOS_LOG_H
#define LIBAOS_LOG_H
#include <string.h>
#ifdef __cplusplus
extern "C"
{
#endif
typedef enum {
AOS_LOG_OFF = 1,
AOS_LOG_FATAL,
AOS_LOG_ERROR,
AOS_LOG_WARN,
AOS_LOG_INFO,
AOS_LOG_DEBUG,
AOS_LOG_TRACE,
AOS_LOG_ALL
} aos_log_level_e;
extern aos_log_level_e aos_log_level;
void aos_log_format(int level,
const char *file,
int line,
const char *function,
const char *fmt, ...);
void aos_print_log_android(int level, char *log);
void aos_log_set_level(aos_log_level_e level);
#ifdef __ANDROID__
#define print_log(level, log) aos_print_log_android(level, log)
#else
#define print_log(level, log) puts(log)
#endif
#ifdef WIN32
#define __FL_NME__ (strchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#define aos_fatal_log(format, ...) if(aos_log_level>=AOS_LOG_FATAL) \
aos_log_format(AOS_LOG_FATAL, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_error_log(format, ...) if(aos_log_level>=AOS_LOG_ERROR) \
aos_log_format(AOS_LOG_ERROR, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_warn_log(format, ...) if(aos_log_level>=AOS_LOG_WARN) \
aos_log_format(AOS_LOG_WARN, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_info_log(format, ...) if(aos_log_level>=AOS_LOG_INFO) \
aos_log_format(AOS_LOG_INFO, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_debug_log(format, ...) if(aos_log_level>=AOS_LOG_DEBUG) \
aos_log_format(AOS_LOG_DEBUG, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#define aos_trace_log(format, ...) if(aos_log_level>=AOS_LOG_TRACE) \
aos_log_format(AOS_LOG_TRACE, __FL_NME__, __LINE__, __FUNCTION__, format, __VA_ARGS__)
#else
#define __FL_NME__ (strchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#define aos_fatal_log(format, args...) if(aos_log_level>=AOS_LOG_FATAL) \
aos_log_format(AOS_LOG_FATAL, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_error_log(format, args...) if(aos_log_level>=AOS_LOG_ERROR) \
aos_log_format(AOS_LOG_ERROR, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_warn_log(format, args...) if(aos_log_level>=AOS_LOG_WARN) \
aos_log_format(AOS_LOG_WARN, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_info_log(format, args...) if(aos_log_level>=AOS_LOG_INFO) \
aos_log_format(AOS_LOG_INFO, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_debug_log(format, args...) if(aos_log_level>=AOS_LOG_DEBUG) \
aos_log_format(AOS_LOG_DEBUG, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#define aos_trace_log(format, args...) if(aos_log_level>=AOS_LOG_TRACE) \
aos_log_format(AOS_LOG_TRACE, __FL_NME__, __LINE__, __FUNCTION__, format, ## args)
#endif
#ifdef __cplusplus
}
#endif
#endif
This diff is collapsed.
#ifndef LIBLOG_API_H
#define LIBLOG_API_H
#include "log_define.h"
#include "log_producer_config.h"
#include "log_builder.h"
LOG_CPP_START
#ifdef WIN32
#undef interface
#endif // WIN32
struct _log_post_option
{
char * interface; // net interface to send log, NULL as default
int connect_timeout; // connection timeout seconds, 0 as default
int operation_timeout; // operation timeout seconds, 0 as default
int compress_type; // 0 no compress, 1 lz4
int ntp_time_offset; //time offset between local time and server time
int using_https; // 0 http, 1 https
int mode; // 0, LoadBalance; 1 KeyShard
char *shardKey;
};
typedef struct _log_post_option log_post_option;
log_status_t sls_log_init();
void sls_log_destroy();
post_log_result * post_logs_from_lz4buf(const char *endpoint, const char * accesskeyId, const char *accessKey, const char *stsToken, const char *project, const char *logstore, lz4_log_buf * buffer, log_post_option * option);
post_log_result * post_logs_from_lz4buf_with_config(log_producer_config *config, const char *endpoint, const char *project, const char *logstore, const char *accessKeyId, const char *accessKeySecret, const char *stsToken, lz4_log_buf *buffer, log_post_option *option);
post_log_result * post_logs_from_lz4buf_webtracking(const char *endpoint, const char *project, const char *logstore, lz4_log_buf *buffer, log_post_option *option);
void post_log_result_destroy(post_log_result * result);
LOG_CPP_END
#endif
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment