PageRenderTime 66ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/analytics/misc/log-analytics/README.md

https://gitlab.com/yasminmostfa/thomas-site
Markdown | 361 lines | 262 code | 99 blank | 0 comment | 0 complexity | 88281a231da9728197e91848fbb49af9 MD5 | raw file
  1. # Piwik Server Log Analytics
  2. Import your server logs in Piwik with this powerful and easy to use tool.
  3. ## Requirements
  4. * Python 2.6 or 2.7. Python 3.x is not supported.
  5. * Piwik >= 2.14.0
  6. Build status (master branch) [![Build Status](https://travis-ci.org/piwik/piwik-log-analytics.svg?branch=master)](https://travis-ci.org/piwik/piwik-log-analytics)
  7. ## Supported log formats
  8. The script will import all standard web server log files, and some files with non-standard formats. The following log formats are supported:
  9. * all default log formats for: Nginx, Apache, IIS, Tomcat
  10. * all log formats commonly used such as: NCSA Common log format, Extended log format, W3C Extended log files, Nginx JSON
  11. * log files of some popular Cloud Saas services: Amazon CloudFront logs, Amazon S3 logs
  12. * streaming media server log files such as: Icecast
  13. * log files with and without the virtual host will be imported
  14. In general, many fields are left optional to make the log importer very flexible.
  15. ## Get involved
  16. We're looking for contributors! Feel free to submit Pull requests on Github.
  17. ### Submit a new log format
  18. The Log Analytics importer is designed to detect and import into Piwik as many log files as possible. Help us add your log formats!
  19. * Implement your new log format in the import_logs.py file (look for `FORMATS = {` variable where the log formats are defined),
  20. * Add a new test in [tests/tests.py](https://github.com/piwik/piwik-log-analytics/blob/master/tests/tests.py),
  21. * Test that the logs are imported successfully as you expected,
  22. * Open a Pull Request,
  23. * Check the test you have added works (the build should be green),
  24. * One Piwik team member will review and merge the Pull Request as soon as possible.
  25. We look forward to your contributions!
  26. ### Improve this guide
  27. This readme page could be improved and maybe you would like to help? feel free to create a "edit" this page and create a pull request.
  28. ### Implement new features or fixes
  29. if you're a Python developer and would like to contribute to open source log importer, check out the [list of issues for import_logs.py](https://github.com/piwik/piwik-log-analytics/issues) which lists all issues and suggestions.
  30. ## How to use this script?
  31. The most simple way to import your logs is to run:
  32. ./import_logs.py --url=piwik.example.com /path/to/access.log
  33. You must specify your Piwik URL with the `--url` argument.
  34. The script will automatically read your config.inc.php file to get the authentication
  35. token and communicate with your Piwik install to import the lines.
  36. The default mode will try to mimic the Javascript tracker as much as possible,
  37. and will not track bots, static files, or error requests.
  38. If you wish to track all requests the following command would be used:
  39. python /path/to/piwik/misc/log-analytics/import_logs.py --url=http://mysite/piwik/ --idsite=1234 --recorders=4 --enable-http-errors --enable-http-redirects --enable-static --enable-bots access.log
  40. ### Format Specific Details
  41. * If you are importing Netscaler log files, make sure to specify the `--iis-time-taken-secs` option. Netscaler stores
  42. the time-taken field in seconds while most other formats use milliseconds. Using this option will ensure that the
  43. log importer interprets the field correctly.
  44. ## How to import your logs automatically every day?
  45. You must first make sure your logs are automatically rotated every day. The most
  46. popular ways to implement this are using either:
  47. * logrotate: http://www.linuxcommand.org/man_pages/logrotate8.html
  48. It will work with any HTTP daemon.
  49. * rotatelogs: http://httpd.apache.org/docs/2.0/programs/rotatelogs.html
  50. Only works with Apache.
  51. * let us know what else is useful and we will add it to the list
  52. Your logs should be automatically rotated and stored on your webserver, for instance in daily logs
  53. `/var/log/apache/access-%Y-%m-%d.log` (where %Y, %m and %d represent the year,
  54. month and day).
  55. You can then import your logs automatically each day (at 0:01). Setup a cron job with the command:
  56. 0 1 * * * /path/to/piwik/misc/log-analytics/import-logs.py -u piwik.example.com `date --date=yesterday +/var/log/apache/access-\%Y-\%m-\%d.log`
  57. ## Using Basic access authentication
  58. If you protect your site with Basic access authentication then you can pass the credentials via your
  59. cron job.
  60. Apache configuration:
  61. ```
  62. <Location /piwik>
  63. AuthType basic
  64. AuthName "Site requires authentication"
  65. # Where all the external login/passwords are
  66. AuthUserFile /etc/apache2/somefile
  67. Require valid-user
  68. </Location>
  69. ```
  70. cron job:
  71. ```
  72. 5 0 * * * /var/www/html/piwik/misc/log-analytics/import_logs.py --url https://www.mysite.com/piwik --auth-user=someuser --auth-password=somepassword --exclude-path=/piwik/index.php --enable-http-errors --enable-reverse-dns --idsite=1 date --date=yesterday +/var/log/apache2/access-ssl-\%Y-\%m-\%d.log > /opt/scripts/import-logs.log
  73. ```
  74. Security tips:
  75. * Currently the credentials are not encrypted in the cron job. This should be a future enhancement.
  76. * Always use HTTPS with Basic access authentication to ensure you are not passing credentials clear text.
  77. ## Performance
  78. With an Intel Core i5-2400 @ 3.10GHz (2 cores, 4 virtual cores with Hyper-threading),
  79. running Piwik and its MySQL database, between 250 and 300 records were imported per second.
  80. The import_logs.py script needs CPU to read and parse the log files, but it is actually
  81. Piwik server itself (i.e. PHP/MySQL) which will use more CPU during data import.
  82. To improve performance,
  83. 1. by default, the script one thread to parse and import log lines.
  84. you can use the `--recorders` option to specify the number of parallel threads which will
  85. import hits into Piwik. We recommend to set `--recorders=N` to the number N of CPU cores
  86. that the server hosting Piwik has. The parsing will still be single-threaded,
  87. but several hits will be tracked in Piwik at the same time.
  88. 2. the script will issue hundreds of requests to piwik.php - to improve the Piwik webserver performance
  89. you can disable server access logging for these requests.
  90. Each Piwik webserver (Apache, Nginx, IIS) can also be tweaked a bit to handle more req/sec.
  91. ## Advanced uses
  92. ### Example Nginx Virtual Host Log Format
  93. This log format can be specified for nginx access logs to capture multiple virtual hosts:
  94. * `log_format vhosts '$host $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';`
  95. * `access_log /PATH/TO/access.log vhosts;`
  96. When executing import_logs.py, `--log-format-name=common_complete`.
  97. ### How do I import Page Speed Metric from logs?
  98. In Piwik> Actions> Page URLs and Page Title reports, Piwik reports the Avg. generation time, as an indicator of your website speed.
  99. This metric works by default when using the Javascript tracker, but you can use it with log file as well.
  100. Apache can log the generation time in microseconds using `%D` in the LogFormat.
  101. This metric can be imported using a custom log format in this script.
  102. In the command line, add the `--log-format-regex` parameter that contains the group `generation_time_micro`.
  103. Here's an example:
  104. ```
  105. Apache LogFormat "%h %l %u %t \"%r\" %>s %b %D"
  106. --log-format-regex="(?P<ip>\S+) \S+ \S+ \[(?P<date>.*?) (?P<timezone>.*?)\] \"\S+ (?P<path>.*?) \S+\" (?P<status>\S+) (?P<length>\S+) (?P<generation_time_micro>\S+)"
  107. ```
  108. Note: the group `<generation_time_milli>` is also available if your server logs generation time in milliseconds rather than microseconds.
  109. ### How do I setup Nginx to directly imports in Piwik via syslog?
  110. With the syslog patch from http://wiki.nginx.org/3rdPartyModules which is compiled in dotdeb's release, you can log to syslog and imports them live to Piwik.
  111. Path: Nginx -> syslog -> (syslog central server) -> this script -> piwik
  112. You can use any log format that this script can handle, like Apache Combined, and Json format which needs less processing.
  113. ##### Setup Nginx logs
  114. ```
  115. http {
  116. ...
  117. log_format piwik '{"ip": "$remote_addr",'
  118. '"host": "$host",'
  119. '"path": "$request_uri",'
  120. '"status": "$status",'
  121. '"referrer": "$http_referer",'
  122. '"user_agent": "$http_user_agent",'
  123. '"length": $bytes_sent,'
  124. '"generation_time_milli": $request_time,'
  125. '"date": "$time_iso8601"}';
  126. ...
  127. server {
  128. ...
  129. access_log syslog:info piwik;
  130. ...
  131. }
  132. }
  133. ```
  134. ##### Setup syslog-ng
  135. This is the config for the central server if any. If not, you can also use this config on the same server as Nginx.
  136. ```
  137. options {
  138. stats_freq(600); stats_level(1);
  139. log_fifo_size(1280000);
  140. log_msg_size(8192);
  141. };
  142. source s_nginx { udp(); };
  143. destination d_piwik {
  144. program("/usr/local/piwik/piwik.sh" template("$MSG\n"));
  145. };
  146. log { source(s_nginx); filter(f_info); destination(d_piwik); };
  147. ```
  148. ##### piwik.sh
  149. Just needed to configure the best params for import_logs.py :
  150. ```
  151. #!/bin/sh
  152. exec python /path/to/misc/log-analytics/import_logs.py \
  153. --url=http://localhost/ \
  154. --idsite=1 --recorders=4 --enable-http-errors --enable-http-redirects --enable-static --enable-bots \
  155. --log-format-name=nginx_json -
  156. ```
  157. ##### Example of regex for syslog format (centralized logs)
  158. ###### log format exemple
  159. ```
  160. Aug 31 23:59:59 tt-srv-name www.tt.com: 1.1.1.1 - - [31/Aug/2014:23:59:59 +0200] "GET /index.php HTTP/1.0" 200 3838 "http://www.tt.com/index.php" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0" 365020 www.tt.com
  161. ```
  162. ###### Corresponding regex
  163. ```
  164. --log-format-regex='.* ((?P<ip>\S+) \S+ \S+ \[(?P<date>.*?) (?P<timezone>.*?)\] "\S+ (?P<path>.*?) \S+" (?P<status>\S+) (?P<length>\S+) "(?P<referrer>.*?)" "(?P<user_agent>.*?)").*'
  165. ```
  166. ### Setup Apache CustomLog that directly imports in Piwik
  167. Since apache CustomLog directives can send log data to a script, it is possible to import hits into piwik server-side in real-time rather than processing a logfile each day.
  168. This approach has many advantages, including real-time data being available on your piwik site, using real logs files instead of relying on client-side Javacsript, and not having a surge of CPU/RAM usage during log processing.
  169. The disadvantage is that if Piwik is unavailable, logging data will be lost. Therefore we recommend to also log into a standard log file. Bear in mind also that apache processes will wait until a request is logged before processing a new request, so if piwik runs slow so does your site: it's therefore important to tune `--recorders` to the right level.
  170. ##### Basic setup example
  171. You might have in your main config section:
  172. ```
  173. # Set up your log format as a normal extended format, with hostname at the start
  174. LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" myLogFormat
  175. # Log to a file as usual
  176. CustomLog /path/to/logfile myLogFormat
  177. # Log to piwik as well
  178. CustomLog "|/path/to/import_logs.py --option1 --option2 ... -" myLogFormat
  179. ```
  180. Note: on Debian/Ubuntu, the default configuration defines the `vhost_combined` format. You can use it instead of defining `myLogFormat`.
  181. Here is another example on Apache defining the custom log:
  182. ```
  183. LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" piwikLogFormat
  184. CustomLog "||/var/www/virtual/test.tld/piwik/htdocs/misc/log-analytics/import_logs.py \
  185. --debug --enable-http-errors --enable-http-redirects --enable-bots \
  186. --url=http://piwik.test.tld --output=/var/log/piwik.log --recorders=1 \
  187. --recorder-max-payload-size=1 --log-format-name=common_complete \
  188. -" piwikLogFormat
  189. ```
  190. Useful options here are:
  191. * `--add-sites-new-hosts` (creates new websites in piwik based on %v in the LogFormat)
  192. * `--output=/path/to/piwik.log` (puts any output into a log file for reference/debugging later)
  193. * `--recorders=4` (use whatever value seems sensible for you - higher traffic sites will need more recorders to keep up)
  194. * `-` so it reads straight from /dev/stdin
  195. You can have as many CustomLog statements as you like. However, if you define any CustomLog directives within a <VirtualHost> block, all CustomLogs in the main config will be overridden. Therefore if you require custom logging for particular VirtualHosts, it is recommended to use mod_macro to make configuration more maintainable.
  196. ##### Advanced setup: Apache vhost, custom logs, automatic website creation
  197. As a rather extreme example of what you can do, here is an apache config with:
  198. * standard logging in the main config area for the majority of VirtualHosts
  199. * customised logging in a particular virtualhost to change the hostname (for instance, if a particular virtualhost should be logged as if it were a different site)
  200. * customised logging in another virtualhost which creates new websites in piwik for subsites (e.g. to have domain.com/subsite1 as a whole website in its own right). This requires setting up a custom `--log-format-regex` to allow "/" in the hostname section (NB the escaping necessary for apache to pass through the regex to piwik properly), and also to have multiple CustomLog directives so the subsite gets logged to both domain.com and domain.com/subsite1 websites in piwik
  201. * we also use mod_rewrite to set environment variables so that if you have multiple subsites with the same format , e.g. /subsite1, /subsite2, etc, you can automatically create a new piwik website for each one without having to configure them manually
  202. NB use of mod_macro to ensure consistency and maintainability
  203. Apache configuration source code:
  204. ```
  205. # Set up macro with the options
  206. # * $vhost (this will be used as the piwik website name),
  207. # * $logname (the name of the LogFormat we're using),
  208. # * $output (which logfile to save import_logs.py output to),
  209. # * $env (CustomLog can be set only to fire if an environment variable is set - this contains that environment variable, so subsites only log when it's set)
  210. # NB the --log-format-regex line is exactly the same regex as import_logs.py's own 'common_vhost' format, but with "\/" added in the "host" section's allowed characters
  211. <Macro piwiklog $vhost $logname $output $env>
  212. LogFormat "$vhost %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" $logname
  213. CustomLog "|/path/to/piwik/misc/log-analytics/import_logs.py \
  214. --add-sites-new-hosts \
  215. --config=/path/to/piwik/config/config.ini.php \
  216. --url='http://your.piwik.install/' \
  217. --recorders=4 \
  218. --log-format-regex='(?P<host>[\\\\w\\\\-\\\\.\\\\/]*)(?::\\\\d+)? (?P<ip>\\\\S+) \\\\S+ \\\\S+ \\\\[(?P<date>.*?) (?P<timezone>.*?)\\\\] \\\"\\\\S+ (?P<path>.*?) \\\\S+\\\" (?P<status>\\\\S+) (?P<length>\\\\S+) \\\"(?P<referrer>.*?)\\\" \\\"(?P<user_agent>.*?)\\\"' \
  219. --output=/var/log/piwik/$output.log \
  220. -" \
  221. $logname \
  222. $env
  223. </Macro>
  224. # Set up main apache logging, with:
  225. # * normal %v as hostname,
  226. # * vhost_common as logformat name,
  227. # * /var/log/piwik/main.log as the logfile,
  228. # * no env variable needed since we always want to trigger
  229. Use piwiklog %v vhost_common main " "
  230. <VirtualHost>
  231. ServerName example.com
  232. # Set this host to log to piwik with a different hostname (and using a different output file, /var/log/piwik/example_com.log)
  233. Use piwiklog "another-host.com" vhost_common example_com " "
  234. </VirtualHost>
  235. <VirtualHost>
  236. ServerName domain.com
  237. # We want to log this normally, so repeat the CustomLog from the main section
  238. # (if this is omitted, our other CustomLogs below will override the one in the main section, so the main site won't be logged)
  239. Use piwiklog %v vhost_common main " "
  240. # Now set up mod_rewrite to detect our subsites and set up new piwik websites to track just hits to these (this is a bit like profiles in Google Analytics).
  241. # We want to match domain.com/anothersubsite and domain.com/subsite[0-9]+
  242. # First to be on the safe side, unset the env we'll use to test if we're in a subsite:
  243. UnsetEnv vhostLogName
  244. # Subsite definitions. NB check for both URI and REFERER (some files used in a page, or downloads linked from a page, may not reside within our subsite directory):
  245. # Do the one-off subsite first:
  246. RewriteCond %{REQUEST_URI} ^/anothersubsite(/|$) [OR]
  247. RewriteCond %{HTTP_REFERER} domain\.com/anothersubsite(/|$)
  248. RewriteRule ^/.* - [E=vhostLogName:anothersubsite]
  249. # Subsite of the form /subsite[0-9]+. NB the capture brackets in the RewriteCond rules which get mapped to %1 in the RewriteRule
  250. RewriteCond %{REQUEST_URI} ^/(subsite[0-9]+)(/|$)) [OR]
  251. RewriteCond %{HTTP_REFERER} domain\.com/(subsite[0-9]+)(/|$)
  252. RewriteRule ^/.* - [E=vhostLogName:subsite%1]
  253. # Now set the logging to piwik setting:
  254. # * the hostname to domain.com/<subsitename>
  255. # * the logformat to vhost_domain_com_subsites (can be anything so long as it's unique)
  256. # * the output to go to /var/log/piwik/domain_com_subsites.log (again, can be anything)
  257. # * triggering only when the env variable is set, so requests to other URIs on this domain don't call this logging rule
  258. Use piwiklog domain.com/%{vhostLogName}e vhost_domain_com_subsites domain_com_subsites env=vhostLogName
  259. </VirtualHost>
  260. ```
  261. ### And that's all !
  262. ***This documentation is a community effort, we welcome your pull requests to [improve this documentation](https://github.com/piwik/piwik-log-analytics/edit/master/README.md).***