Giter Site home page Giter Site logo

logsene-cli's Introduction

Build Status

Logsene CLI

Logsene Command-line Interface

Enables searching Logsene log entries from the command-line. Currently supports OS X and Linux.

Installation

npm install logsene-cli -g

or

git clone https://github.com/sematext/logsene-cli.git
cd logsene-cli && npm install
npm link

To test, simply run:

npm test

Logsene

Logsene is a centralized log management solution. You basically upload your logs in bulk or real-time from all your servers. Those logs are then aggregated by time and shown in the Logsene web application, where you have the ability to search for specific terms, narrow down time ranges, filter fields, setup alerts, ...

Logsene Web APP

A quick rundown of most notable features of Logsene:

  • All your logs accessible in one place
  • Control who sees which data
  • Be up and running within minutes -- there is nothing to install or maintain
  • Log Alerts & Anomaly Detection
  • Saved Searches
  • Scheduled Reporting
  • CoreOS Log Collection
  • Docker container monitoring
  • REST API

Shipping logs with node.js

Our other project logagent-js can be used to parse and ship logs to Logsene, both from your JavaScript source or from the command line.

Logsene CLI

Logsene CLI gives you capability to search through your logs from the command line, which brings the awesome benefit of being able to pipe results to awk, sed, cut, sort, head and other friends from the *nix command-line.

Imagine a situation where you suspected that your site were under a DoS attack.
You'd be interested in quickly finding out the top offenders. Here’s a one-liner that shows top originating IP addresses in the last 10 minutes (also shows how to use the -f switch to specify which field(s) to return - field host, in this example):

$ logsene search -t 10m -f host | sort | uniq -c | sort -r | head -n20

Top IPs

You can find more useful examples in the blog post that announced the release of Logsene CLI.

Logsene CLI Session

We define L-CLI session as a set of commands issued by an user, with no more than 30m between them. Every session has a set of configuration parameters that control the way L-CLI behaves. E.g. which Region is used, which Sematext account is used (--api-key); which Logsene application is used (--token); is tracing information going to be displayed (--trace).

For controlling those settings, we use config set and config get commands. For convenience reasons, you don't have to deal with API and APP keys manually. L-CLI automatically retrieves region and both api-key and token keys on each session start, as users login and choose Logsene application. L-CLI then writes those parameters to the session configuration store and reuses them on each subsequent command, until the session times out (after 30m of inactivity).

Login image

The session primitives were introduced in order to enable frictionless multi-user experience, where all users may possibly be accessing L-CLI from the same box (while being SSHd into it), using the same Sematext account and possibly even the same Logsene application.

Commands

logsene search

Usage: logsene search [query] [OPTIONS]
  where OPTIONS may be:
    -q <query>      Query string (-q parameter can be omitted)
    -f <fields>     OPTIONAL Fields to return (defaults to all fields)
    -t <interval>   OPTIONAL datetime, duration or range (defaults to last hour)
    -s <size>       OPTIONAL Number of matches to return (defaults to 200)
    -o <offset>     OPTIONAL Number of matches to skip from the beginning (defaults to 0)
    -op AND         OPTIONAL Overrides default OR operator between multiple query terms
    --json          OPTIONAL Returns log entries in JSON instead of TSV format
    --sep           OPTIONAL Sets the separator between start and end of time ranges

Examples:
  logsene search
      returns last 1h of log entries
      note: default return limit of 200 hits is always in effect unless you
            explicitly change it with the -s switch (where -s without params
            disables the limit altogether)

  logsene search -q ERROR
      returns last 1h of log entries that contain the term ERROR

  logsene search ERROR
      equivalent to the previous example

  logsene search UNDEFINED SEGFAULT
      returns last 1h of log entries that have either of the terms
      note: default operator is OR

  logsene search SEGFAULT Segmentation -op AND
      returns last 1h of log entries that have both terms
      note: convenience parameter --and has the same effect

  logsene search -q "Server not responding"
      returns last 1h of log entries that contain the given phrase

  logsene search "rare thing" -t 1y8M4d8h30m2s
      returns all the log entries that contain the phrase "rare thing" reaching
      back to 1 year 8 months 4 days 8 hours 30 minutes and 2 seconds
      note: when specifying duration, any datetime designator character can be
            omited (shown in the following two examples)
      note: months must be specified with uppercase M (distinction from minutes)
      note: minutes (m) are the default, so "m" can be omited

  logsene search -t 1h30m
      returns all the log entries from the last 1,5h

  logsene search -t 90
      equivalent to the previous example (default time unit is minute)

  logsene search -t 2015-06-20T20:48
      returns all the log entries that were logged after the provided datetime
      note: allowed formats listed at the bottom of this help message

  logsene search -t "2015-06-20 20:28"
      returns all the log entries that were logged after the provided datetime
      note: if a parameter contains spaces, it must be enclosed in quotes

  logsene search -t 2015-06-16T22:27:41/2015-06-18T22:27:41
      returns all the log entries between the two provided timestamps
      note: date range must either contain forward slash between datetimes,
            or a different range separator must be specified (next example)

  logsene search -t "2015-06-16T22:27:41 TO 2015-06-18T22:27:41" --sep " TO "
      same as previous command, except it sets the custom string separator that
      denotes a range
      note: default separator is the forward slash (as per ISO-8601)
      note: if a parameter contains spaces, it must be enclosed in quotes

  logsene search -t "last Friday at 13/last Friday at 13:30"
      it is also possible to use "human language" to designate datetime
      note: it may be used only in place of datetime. Expressing range is not
            possible (e.g. "last friday between 12 and 14" is not allowed)
      note: may yield unpredictable datetime values

  logsene search -q ERROR -s 20
      returns at most 20 log entries (within the last hour) with the term ERROR

  logsene search ERROR -s 50 -o 20
      returns chronologically sorted hits 21st to 71st (offset is 20)
      note: default sort order is ascending (latest entries at the bottom)

  logsene search --help
      outputs this usage information

Allowed datetime formats:
  YYYY[-]MM[-]DD(T, )[HH[:MM[:SS]]]
  e.g.
    YYYY-MM-DD HH:mm:ss
    YYYY-MM-DDTHH:mm
    YYYY-MM-DDHH:mm
    YYYYMMDDTHH:mm
    YYYYMMDD HH:mm
    YYYY-MM-DD
    YYYYMMDD
    YYYY-MM-DD HHmm
    YYYYMMDD HHmm
    YYYY-MM-DDTHHmm
    YYYYMMDDTHH:mm
    YYYYMMDDTHHmm
    YYYYMMDDTHH:mm
    YYYY-MM-DDTHHmmss
    YYYYMMDDHHmmss
  note: date part may be separated from time by T (ISO-8601) or space
  note: if datetime contains a space, it must be enclosed in double quotes

Allowed duration format:
  [Ny][NM][Nd][Nh][Nm][Ns]
  e.g.
    1y2M8d22h8m48s
  note: uppercase M must be used for months, lowercase m for minutes
  note: if only a number is specified, it defaults to minutes

Allowed range formats
  range can be expressed in all datetime/duration combinations:
  datetime/datetime
  datetime/(+|-)duration
  duration/(+|-)duration
  duration/datetime
  note: / is default range separator; + or - sign is duration direction
  note: duration must begin with either + or - when used in end of range position

  The following table shows how ranges are calculated, given the different input parameters
┌──────────────────────────────────────┬─────────────────────────────┬──────────────────────┐
│ -t parameter                         │ range start                 │ range end            │
├──────────────────────────────────────┼─────────────────────────────┼──────────────────────┤
│ 2016-06-24T18:42                     │ timestamp                   │ now                  │
├──────────────────────────────────────┼─────────────────────────────┼──────────────────────┤
│ 2016-06-24T18:42/2016-06-24T18:52:30 │ timestamp                   │ timestamp            │
├──────────────────────────────────────┼─────────────────────────────┼──────────────────────┤
│ 2016-06-24T18:42/+1d                 │ timestamp                   │ timestamp + duration │
├──────────────────────────────────────┼─────────────────────────────┼──────────────────────┤
│ 2016-06-24T18:42/-1d                 │ timestamp - duration        │ timestamp            │
├──────────────────────────────────────┼─────────────────────────────┼──────────────────────┤
│ 2h30m8s                              │ now - duration              │ now                  │
├──────────────────────────────────────┼─────────────────────────────┼──────────────────────┤
│ 2h/+1h                               │ now - duration1             │ start + duration2    │
├──────────────────────────────────────┼─────────────────────────────┼──────────────────────┤
│ 2h/-1h                               │ now - duration1 - duration2 │ now - duration1      │
├──────────────────────────────────────┼─────────────────────────────┼──────────────────────┤
│ 5d10h25/2016-06-24T18:42             │ now - duration              │ timestamp            │
└──────────────────────────────────────┴─────────────────────────────┴──────────────────────┘
  note: all allowable datetime formats are also permitted when specifying ranges
  note: disallowed range separators:
       Y, y, M, D, d, H, h, m, S, s, -, +, P, p, T, t

Allowed "human" formats (all in local time):
    10 minutes ago
    yesterday at 12:30pm
    last night (night becomes 19:00)
    last month
    last friday at 2pm
    3 hours ago
    2 weeks ago at 17
    wednesday 2 weeks ago
    2 months ago
    last week saturday morning (morning becomes 06:00)
  note: "human" format can only be used instead of date-time
  note: it is not possible to express duration with "human" format (e.g. "from 2 to 3 this morining")
  note: it is recommended to avoid human format, as it may yield unexpected results

logsene config set

Usage: logsene config set [OPTIONS]
  where OPTIONS may be:
    --api-key <apiKey>
    --token <appToken>
    --default-size <size>
    --range-separator <sep>
    --trace <true|false>

It is not necessary to explicitly set api-key nor token.
Logsene CLI will ask you to log in and choose Logsene application
if keys are missing from the configuration
Examples:
  logsene config set --api-key 11111111-1111-1111-1111-111111111111
      sets the api key for the current session

  logsene config set --token 22222222-2222-2222-2222-222222222222
      sets Logsene application key for the current session

  logsene config set --default-size 3000
      sets default number of hits returned for the current session (overrides the default 200)

  logsene config set --range-separator TO
      sets default separator of two datetimes for time ranges (default is /, as per ISO6801)

  logsene config set --trace [true]
      activates tracing for the current session (true can be omitted)

  logsene config set --trace false
      deactivates tracing for the current session

logsene config get

Usage: logsene config get [OPTION]  Where OPTION may be:
    --api-key
    --token
    --app-name
    --default-size (sets the default number of hits returned for the current session)
    --range-separator (used to separate start and end of a time range)
    --trace
    --region (which region has been set during login - US or EU)
    --all (return listing of all params from the current user's session)

Changelog

2.3.0 - 2019-02-05

  • add region selection to login
  • add http Authorization header for ES requests
  • remove deprecated _cache ES search payload parameter 2.2.0 - 2018-02-20
  • apply fields param to _source (unlike previous stored_fields and fields param) 2.1.1 - 2018-02-20
  • fixed fields bug and adjusted param name (ES version compatibility: fields -> stored_fields)

logsene-cli's People

Contributors

mbonaci avatar megastef avatar otisg avatar mduvanel avatar dependabot[bot] avatar prog8 avatar

Stargazers

Suri avatar Jan Antala avatar Nedim Šabić² avatar  avatar Aravindo Wingeier avatar Luka Kakia avatar  avatar Vladimir Tretyakov avatar Philippe Koenig avatar  avatar

Watchers

 avatar mingfeng.zhang avatar regiluze avatar Rafał Kuć avatar James Cloos avatar Vladimir Tretyakov avatar Soham Chakraborty avatar Erol Mujak avatar Fex Core avatar Davor Obilinović avatar Tien Nguyen avatar Euan Clark avatar  avatar  avatar Nedim Šabić² avatar John Demian avatar Nicolaegis avatar Bora Tanrikulu avatar Costas Pipilas avatar  avatar

logsene-cli's Issues

Add logout command

Now that users have to choose region during login, we should allow them to logout from the active session in order to switch between regions and Log applications.

Currently, the only way to force logout (short of waiting 30 min) is to manually delete the session config file at ~/.config/configstore/logsene/<user>.json or to remove apiKey and/or token from it.

SSL & proxy issues

I think I am not able to use logsene-cli because of the corporate proxy.

$ logsene config set --app-key 1111-2222-333-444-555
No active sessions. Please log in using your Sematext account:
Enter your username: xxx
Enter your password: 
◓/usr/local/lib/node_modules/logsene-cli/lib/logsene-api.js:68
    out.trace('Login error.\n' + err.data.toString());  // materialize buf
                                         ^
TypeError: Cannot read property 'toString' of undefined
    at Request.fn [as _callback] (/usr/local/lib/node_modules/logsene-cli/lib/logsene-api.js:68:46)
    at self.callback (/usr/local/lib/node_modules/logsene-cli/node_modules/request/request.js:198:22)
    at Request.emit (events.js:107:17)
    at Request.onRequestError (/usr/local/lib/node_modules/logsene-cli/node_modules/request/request.js:867:8)
    at ClientRequest.emit (events.js:107:17)
    at ClientRequest.onError (/usr/local/lib/node_modules/logsene-cli/node_modules/tunnel-agent/index.js:176:21)
    at ClientRequest.g (events.js:199:16)
    at ClientRequest.emit (events.js:107:17)
    at TLSSocket.socketErrorListener (_http_client.js:271:9)
    at TLSSocket.emit (events.js:129:20)
    at onwriteError (_stream_writable.js:317:10)
    at onwrite (_stream_writable.js:335:5)
    at WritableState.onwrite (_stream_writable.js:105:5)
    at fireErrorCallbacks (net.js:456:13)
    at TLSSocket.Socket._destroy (net.js:495:3)
    at WriteWrap.afterWrite (net.js:777:10)

If I skip undefined print I get something like

Login was not successful{"jse_shortmsg":"Error while logging in.","jse_summary":"Error while logging in.: tunneling socket could not be established, cause=write EPROTO 140176374314816:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:782:\n","jse_cause":{"code":"ECONNRESET"},"message":"Error while logging in.: tunneling socket could not be established, cause=write EPROTO 140176374314816:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:782:\n"}
Unable to login: Login was not successful. Possibly wrong username or password.

Maximum call stack size exceeded on node.js 6.x

I think elasticsearch client dependencies need an update:


logsene search 
events.js:436
EventEmitter.listenerCount = function(emitter, type) {
                                     ^

RangeError: Maximum call stack size exceeded
    at Function.EventEmitter.listenerCount (events.js:436:38)
    at Log.listenerCount (/usr/local/lib/node_modules/logsene-cli/node_modules/elasticsearch/src/lib/log.js:68:25)
    at Function.EventEmitter.listenerCount (events.js:438:20)
    at Log.listenerCount (/usr/local/lib/node_modules/logsene-cli/node_modules/elasticsearch/src/lib/log.js:68:25)
    at Function.EventEmitter.listenerCount (events.js:438:20)
    at Log.listenerCount (/usr/local/lib/node_modules/logsene-cli/node_modules/elasticsearch/src/lib/log.js:68:25)
    at Function.EventEmitter.listenerCount (events.js:438:20)
    at Log.listenerCount (/usr/local/lib/node_modules/logsene-cli/node_modules/elasticsearch/src/lib/log.js:68:25)
    at Function.EventEmitter.listenerCount (events.js:438:20)
    at Log.listenerCount (/usr/local/lib/node_modules/logsene-cli/node_modules/elasticsearch/src/lib/log.js:68:25)
    at Function.EventEmitter.listenerCount (events.js:438:20)
    at Log.listenerCount (/usr/local/lib/node_modules/logsene-cli/node_modules/elasticsearch/src/lib/log.js:68:25)
    at Function.EventEmitter.listenerCount (events.js:438:20)
    at Log.listenerCount (/usr/local/lib/node_modules/logsene-cli/node_modules/elasticsearch/src/lib/log.js:68:25)
    at Function.EventEmitter.listenerCount (events.js:438:20)
    at Log.listenerCount (/usr/local/lib/node_modules/logsene-cli/node_modules/elasticsearch/src/lib/log.js:68:25)

Login doesn't work

When trying logsene search it prompts me to login. I do so, but get

No active sessions. Please log in using your Sematext account:
Enter your username: xxxxxxx
Enter your password:
Login was not successful{}
Unable to login: Login was not successful. Possibly wrong username or password.

Use --token instead of --api-key

--app-key should be --token, because that is the terminology Logsene uses. Using --app-key name instead of --token is confusing, plus there is another very similar parameter (--api-key).

Issue when attempting to specify which fields to bring back using -f

Hi,

I am running into an issue when attempting to specify which fields to bring back using -f

root@956d26155944:~/.config/configstore/logsene# logsene search -q tags:httpd -f request
/usr/local/lib/node_modules/logsene-cli/commands/search.js:65
        opts.body.fields(f);
                  ^

TypeError: opts.body.fields is not a function
    at child._run [as run] (/usr/local/lib/node_modules/logsene-cli/commands/search.js:65:19)
    at /usr/local/lib/node_modules/logsene-cli/node_modules/ronin/lib/command.js:190:4
    at iterate (/usr/local/lib/node_modules/logsene-cli/node_modules/ronin/node_modules/async/lib/async.js:146:13)
    at Timeout._onTimeout (/usr/local/lib/node_modules/logsene-cli/node_modules/ronin/node_modules/async/lib/async.js:157:25)
    at ontimeout (timers.js:458:11)
    at tryOnTimeout (timers.js:296:5)
    at Timer.listOnTimeout (timers.js:259:5)

Error on search: TypeError: Cannot read property 'defaultOperator' of undefined

Login works, but then search does not:

{ ~ }  » logsene search                                                                       ~ 1
TypeError: Cannot read property 'defaultOperator' of undefined
    at _getQuery (D:\dev\apps\node\node_modules\logsene-cli\commands\search.js:344:44)
    at _run [as run] (D:\dev\apps\node\node_modules\logsene-cli\commands\search.js:47:44)
    at D:\dev\apps\node\node_modules\logsene-cli\node_modules\ronin\build\command.js:260:9
    at iterate (D:\dev\apps\node\node_modules\logsene-cli\node_modules\ronin\node_modules\async\lib\async.js:146:13)
    at null._onTimeout (D:\dev\apps\node\node_modules\logsene-cli\node_modules\ronin\node_modules\async\lib\async.js:157:25)
    at tryOnTimeout (timers.js:224:11)
    at Timer.listOnTimeout (timers.js:198:5)

1.4.2 installed over npm on windows 7.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.