### Start LNAV with log files or directories
Source: https://github.com/tstack/lnav/blob/master/README.md
This is the basic command to start LNAV. Point it to the log files or directories you wish to monitor.
```console
$ lnav /path/to/file1 /path/to/dir ...
```
--------------------------------
### Install lnav on FreeBSD
Source: https://github.com/tstack/lnav/blob/master/docs/02_downloads.md
Use the pkg command to install lnav on FreeBSD.
```bash
$ pkg install lnav
```
--------------------------------
### Install lnav using Package Cloud (RPM)
Source: https://github.com/tstack/lnav/blob/master/docs/02_downloads.md
First, add the lnav repository from Package Cloud, then install lnav using yum.
```bash
$ curl -s https://packagecloud.io/install/repositories/tstack/lnav/script.rpm.sh | sudo bash
$ sudo yum install lnav
```
--------------------------------
### Install lnav using Snap
Source: https://github.com/tstack/lnav/blob/master/docs/02_downloads.md
Use this command to install lnav on systems that support Snap packages.
```bash
$ sudo snap install lnav
```
--------------------------------
### Install lnav using Homebrew
Source: https://github.com/tstack/lnav/blob/master/docs/02_downloads.md
Use Homebrew to install lnav on macOS.
```bash
$ brew install lnav
```
--------------------------------
### Executing an Installable Format File
Source: https://github.com/tstack/lnav/blob/master/docs/source/formats.md
After making a format file executable, you can run it directly to install the format. This provides a convenient way to manage custom formats.
```bash
$ chmod ugo+rx myformat.json
$ ./myformat.json
info: installed: /home/example/.lnav/formats/installed/myformat_log.json
```
--------------------------------
### Install freeze
Source: https://github.com/tstack/lnav/blob/master/docs/screenshots/README.md
Install the `freeze` tool, which renders terminal captures to SVG and PNG. This is a prerequisite for generating screenshots.
```shell
brew install charmbracelet/tap/freeze
```
--------------------------------
### Installing a Format File via CLI
Source: https://github.com/tstack/lnav/blob/master/docs/source/formats.md
Install a log format file using the '-i' option with the lnav command. The format will be placed in the 'installed' subdirectory of the lnav formats directory.
```bash
$ lnav -i myformat.json
info: installed: /home/example/.lnav/formats/installed/myformat_log.json
```
--------------------------------
### Making a Format File Executable for Installation
Source: https://github.com/tstack/lnav/blob/master/docs/source/formats.md
Add a shebang line to a format file to make it executable. Executing the file will automatically install the format.
```default
#! /usr/bin/env lnav -i
{
"myformat_log" : ...
}
```
--------------------------------
### Installing Formats from a Git Repository
Source: https://github.com/tstack/lnav/blob/master/docs/source/formats.md
Install a collection of log formats from a git repository by passing 'extra' to the '-i' option. This is useful for using community-maintained format sets.
```bash
lnav -i extra
```
--------------------------------
### Install Rules Configuration
Source: https://github.com/tstack/lnav/blob/master/CMakeLists.txt
Conditionally includes installation rules if CMake is not instructed to skip them.
```cmake
if (NOT CMAKE_SKIP_INSTALL_RULES)
include(cmake/install-rules.cmake)
endif ()
```
--------------------------------
### Build lnav from Source
Source: https://github.com/tstack/lnav/blob/master/docs/02_downloads.md
Download the source tarball, unpack it, and then configure, build, and install lnav.
```bash
$ tar xvfz lnav-{{site.version}}.tar.gz
$ cd lnav-{{site.version}}
$ ./configure
$ make
$ make install
```
--------------------------------
### Install zellij
Source: https://github.com/tstack/lnav/blob/master/docs/screenshots/README.md
Install `zellij`, a terminal multiplexer required to run lnav in a real PTY for correct TUI initialization. This is a prerequisite for generating screenshots.
```shell
brew install zellij
```
--------------------------------
### Build lnav from source
Source: https://github.com/tstack/lnav/blob/master/README.md
Standard GNU build process for lnav. Ensure all prerequisites are installed before running.
```bash
./configure
make
sudo make install
```
--------------------------------
### Connect to the lnav Tutorial Instance
Source: https://github.com/tstack/lnav/blob/master/docs/04_tutorials.md
Use this command to access the interactive tutorial environment hosted on fly.io. No installation is required.
```shell
$ ssh tutorial1@demo.lnav.org
```
--------------------------------
### lnav Query Example
Source: https://github.com/tstack/lnav/blob/master/test/textfile_0.md
Demonstrates basic lnav query syntax for selecting data and filtering logs.
```lnav
;SELECT * FROM syslog_log
:filter-out spam
```
--------------------------------
### Example Syslog Message
Source: https://github.com/tstack/lnav/blob/master/docs/source/data.md
A sample Syslog message from sudo that demonstrates extractable key/value pairs.
```default
Jul 31 11:42:26 Example-MacBook-Pro.local sudo[87024]: testuser : TTY=ttys004 ; PWD=/Users/testuser/github/lbuild ; USER=root ; COMMAND=/usr/bin/make install
```
--------------------------------
### substr(str, start, [size])
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Returns a substring of the input string 'str' starting from the 'start' character and with a length of 'size'. Indexes start at 1. Negative values for 'start' count from the right, and negative values for 'size' return characters before the start.
```APIDOC
## substr(str, start, [size])
### Description
Returns a substring of input string X that begins with the Y-th character and which is Z characters long.
### Parameters
#### Path Parameters
- **str** (string) - The string to extract a substring from.
- **start** (integer) - The index within 'str' that is the start of the substring. Indexes begin at 1. A negative value means that the substring is found by counting from the right rather than the left.
- **size** (integer) - Optional. The size of the substring. If not given, then all characters through the end of the string are returned. If the value is negative, then the characters before the start are returned.
### Examples
```sql
#1 To get the substring starting at the second character until the end of the string 'abc'
SELECT substr('abc', 2)
#2 To get the substring of size one starting at the second character of the string 'abc':
SELECT substr('abc', 2, 1)
#3 To get the substring starting at the last character until the end of the string 'abc':
SELECT substr('abc', -1)
#4 To get the substring starting at the last character and going backwards one step of the string 'abc':
SELECT substr('abc', -1, -1)
```
```
--------------------------------
### HTML Table Example
Source: https://github.com/tstack/lnav/blob/master/test/textfile_0.md
An example of an HTML table with two rows, each containing header and data cells.
```html
```
--------------------------------
### Load and Follow System Syslog
Source: https://github.com/tstack/lnav/blob/master/docs/source/cli.md
Use this command to load and follow the system syslog file. No arguments are needed to start.
```bash
lnav
```
--------------------------------
### Connect SSH Keys Plug for Snap Installation
Source: https://github.com/tstack/lnav/blob/master/docs/source/usage.md
Connects the ssh-keys plug for lnav installed via snap. This is required for remote file access.
```bash
sudo snap connect lnav:ssh-keys
```
--------------------------------
### List Installed lnav Apps
Source: https://github.com/tstack/lnav/blob/master/src/static-files/index.md
This lnav script queries the lnav_apps table to generate an HTML unordered list of installed applications, linking to each app's respective URL. It uses SQL to fetch app names and descriptions, formats them, and then embeds them within an HTML structure.
```lnav
SELECT
group_concat(format('%s - %s',
name,
name,
encode(description, 'html')),
char(10)) AS items
FROM lnav_apps
:echo
```
--------------------------------
### SQL Syntax Error Example
Source: https://github.com/tstack/lnav/blob/master/docs/_posts/2022-08-04-pretty-errors.md
An example of SQL content that would produce a syntax error. This demonstrates the input that triggers the improved error reporting.
```sql
-- This is a test
SELECT abc),
rtrim(def)
FROM mytable;
```
--------------------------------
### Example JSON Log Lines
Source: https://github.com/tstack/lnav/blob/master/docs/_posts/2013-09-10-json-encoded-logs.md
These are example log entries formatted as single-line JSON objects. They are intended for machine processing but can be made human-readable with lnav.
```json
{"time": "2013-09-04T23:55:09.274041Z", "level" : "INFO", "body" : "Hello, World!" }
{"time": "2013-09-04T23:56:00.285224Z", "level" : "ERROR", "body" : "Something terrible has happened!", "tb": " foo.c:12\n bar.y:33" }
```
--------------------------------
### PCRE Regular Expression Example
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
This example shows how to use PCRE (Perl-Compatible Regular Expressions) for searching within lnav. It demonstrates a pattern to find ethernet device names.
```regex
eth\d+
```
--------------------------------
### lnav script example: SELECT and EVAL
Source: https://github.com/tstack/lnav/blob/master/NEWS.md
Example of an lnav script demonstrating how the first row of a SQL query result can be converted into local variables for use in subsequent commands. This script selects the value 1, assigns it to 'foobar', and then echoes it.
```lnav
;SELECT 1 as foobar
:eval :echo ${foobar}
```
--------------------------------
### Select All Columns from a Table
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Query the database and return zero or more rows of data. This example selects all columns from the 'lnav_example_log' table.
```custsqlite
;SELECT * FROM lnav_example_log
log_line log_part log_time log_actual_time log_idle_msecs log_level log_mark log_comment log_tags log_filters ex_procname ex_duration log_time_msecs log_path log_text log_body
0 2017-02⋯:06.100 2017-02⋯:06.100 0 info 0 hw 2 1486094706000 /tmp/log 2017-02⋯ World! Hello, World!
1 2017-02⋯:06.200 2017-02⋯:06.200 100 error 0 gw 4 1486094706000 /tmp/log 2017-02⋯ World! Goodbye, World!
2 new 2017-02⋯:06.200 2017-02⋯:06.200 1200000 warn 0 gw 1 1486095906000 /tmp/log 2017-02⋯ World! Goodbye, World!
3 new 2017-02⋯:06.200 2017-02⋯:06.200 1800000 debug 0 gw 10 1486097706000 /tmp/log 2017-02⋯ World! Goodbye, World!
```
--------------------------------
### Preformatted Text Example
Source: https://github.com/tstack/lnav/blob/master/test/textfile_0.md
Demonstrates how to display preformatted text, including HTML tags within the pre block.
```html
Hello,
World!
```
--------------------------------
### Produce a hash for a string
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Generates a hash for the input string. This example shows a basic usage.
```sql
;SELECT spooky_hash('Hello, World!')
```
--------------------------------
### Get Final lnav Configuration as JSON
Source: https://github.com/tstack/lnav/blob/master/docs/_posts/2023-08-04-config-dump.md
Use the `config get` command in management mode to retrieve the complete configuration lnav is currently using, outputted in JSON format. This helps in understanding the effective settings.
```console
$ lnav -m config get
```
--------------------------------
### Script Description Example
Source: https://github.com/tstack/lnav/blob/master/docs/source/scripts.md
Provides a one-line description of the script's functionality. Used for interactive help.
```default
# @description: Say hello to the given names.
```
--------------------------------
### Test if string starts with a prefix
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Tests if a given string begins with a specified prefix. Useful for prefix matching.
```sql
;SELECT startswith('foobar', 'foo')
```
--------------------------------
### Get the sign of a negative number
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqlext.md
Returns the sign of the given number as -1, 0, or 1. This example shows how to get the sign of -10.
```custsqlite
;SELECT sign(-10)
-1
```
--------------------------------
### Get the sign of a positive number
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqlext.md
Returns the sign of the given number as -1, 0, or 1. This example shows how to get the sign of 10.
```custsqlite
;SELECT sign(10)
1
```
--------------------------------
### Get Row Number within a Partition
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Returns the sequential number of the current row within its partition, starting from 1. This is useful for ranking or numbering rows based on specific criteria.
```custsqlite
;SELECT row_number() OVER (PARTITION BY ex_procname ORDER BY log_line) AS msg_num, ex_procname, log_body FROM lnav_example_log
msg_num ex_procname log_body
1 gw Goodbye, World!
2 gw Goodbye, World!
3 gw Goodbye, World!
1 hw Hello, World!
```
--------------------------------
### Script Synopsis Example
Source: https://github.com/tstack/lnav/blob/master/docs/source/scripts.md
Defines the synopsis for a script, including its name and parameters. Used for interactive help.
```default
# @synopsis: hello-world [ ... ]
```
--------------------------------
### Extract Substring
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Returns a substring from a given string. Indexes start at 1. Negative start indexes count from the right. A negative size returns characters before the start.
```SQL
SELECT substr('abc', 2)
```
```SQL
SELECT substr('abc', 2, 1)
```
```SQL
SELECT substr('abc', -1)
```
```SQL
SELECT substr('abc', -1, -1)
```
--------------------------------
### Find Substring with Start Position
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Searches for a substring within a larger string, starting from a specified position.
```custsqlite
;SELECT charindex('abc', 'abcabc', 2)
4
```
--------------------------------
### Go Integration with PRQL C Library
Source: https://github.com/tstack/lnav/blob/master/src/third-party/lnav-rs-ext/README.md
Example of how to use the PRQL C library in Go to convert PRQL queries to SQL. Ensure the C library is linked correctly using CGO_LDFLAGS.
```go
package prql
/*
#include
int to_sql(char *prql_query, char *sql_query);
int to_json(char *prql_query, char *json_query);
*/
import "C"
import (
"errors"
"strings"
"unsafe"
)
// ToSQL converts a PRQL query to SQL
func ToSQL(prql string) (string, error) {
// buffer length should not be less than 1K because we may get an error
// from the PRQL compiler with a very short query
cStringBufferLength := 1024
// allocate a buffer 3 times the length of the PRQL query to store the
// generated SQL query
if len(prql)*3 > cStringBufferLength {
cStringBufferLength = len(prql) * 3
}
// preallocate the buffer
cstr := C.CString(strings.Repeat(" ", cStringBufferLength))
defer C.free(unsafe.Pointer(cstr))
// convert the PRQL query to SQL
res := C.to_sql(C.CString(prql), cstr)
if res == 0 {
return C.GoString(cstr), nil
}
return "", errors.New(C.GoString(cstr))
}
// ToJSON converts a PRQL query to JSON
func ToJSON(prql string) (string, error) {
// buffer length should not be less than 1K because we may get an error
cStringBufferLength := 1024
if len(prql)*3 > cStringBufferLength {
cStringBufferLength = len(prql) * 10
}
// preallocate the buffer
cstr := C.CString(strings.Repeat(" ", cStringBufferLength))
defer C.free(unsafe.Pointer(cstr))
// convert the PRQL query to SQL
res := C.to_json(C.CString(prql), cstr)
if res == 0 {
return C.GoString(cstr), nil
}
return "", errors.New(C.GoString(cstr))
}
```
--------------------------------
### LIKE Operator Example
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqlext.md
Checks if a string matches a SQL LIKE pattern. The '%' wildcard matches any sequence of zero or more characters.
```custsqlite
;SELECT 'Hello, World!' LIKE 'Hello, %!'
```
--------------------------------
### Test if string does not start with a prefix
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Tests if a given string does not begin with a specified prefix. Useful for negative prefix matching.
```sql
;SELECT startswith('foobar', 'bar')
```
--------------------------------
### Sample Input Log Document
Source: https://github.com/tstack/lnav/blob/master/docs/source/config.md
This is a sample input log document demonstrating the format expected by the demultiplexer configuration. It includes control lines and log entries with source, message, host, and pod information.
```text
===== START =====
2024-12-12T08:00:00.123Z source=service-a This is a log message kubernetes_host=host-a kubernetes_pod_name=pod-1
2024-12-12T08:01:00.456Z source=service-b Another log message kubernetes_host=host-b kubernetes_pod_name=pod-2
===== END =====
```
--------------------------------
### Execute lnav Command to Go to Line
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Use the -c option to execute built-in commands. This example opens 'foo.log' and navigates to the tenth line.
```bash
lnav -c ":goto 10" foo.log
```
--------------------------------
### C Hello World Program
Source: https://github.com/tstack/lnav/blob/master/test/textfile_0.md
A standard 'Hello, World!' program in C, including necessary headers and the main function.
```c
/*
* This program prints "Hello, World!"
*/
#include
int main() {
printf("Hello, World!\n");
}
```
--------------------------------
### Query Access Log with SQL
Source: https://github.com/tstack/lnav/blob/master/docs/03_features.md
Perform SQL queries directly on log files. This example queries an Apache access log to count and sum bytes by client IP.
```sql
SELECT c_ip, count(*), sum(sc_bytes) AS total FROM access_log
GROUP BY c_ip ORDER BY total DESC;
```
--------------------------------
### generate_series(start, stop, [step])
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
A table-valued-function that generates a series of whole numbers between a specified start and stop, inclusive. An optional step parameter can define the increment.
```APIDOC
## generate_series(start, stop, [step])
### Description
A table-valued-function that returns the whole numbers between a lower and upper bound, inclusive.
### Parameters
* **start** (integer) - The starting point of the series.
* **stop** (integer) - The stopping point of the series.
* **step** (integer, optional) - The increment between each value. Defaults to 1.
### Result
* **value** (integer) - The number in the series.
### Examples
```sql
-- To generate the numbers in the range [10, 14]:
SELECT value FROM generate_series(10, 14);
-- To generate every other number in the range [10, 14]:
SELECT value FROM generate_series(10, 14, 2);
-- To count down from five to 1:
SELECT value FROM generate_series(5, 1, -1);
```
```
--------------------------------
### Open Help View
Source: https://github.com/tstack/lnav/blob/master/src/internals/cmd-ref.rst
Opens the help text view to access lnav documentation and command usage.
```lnav
:help
```
--------------------------------
### Access Configuration Panels
Source: https://github.com/tstack/lnav/blob/master/docs/source/ui.md
Press `TAB` to access the Files and Filters configuration panels. Press `q` to hide the panels.
```text
TAB
```
```text
q
```
--------------------------------
### Round Timestamp to Time Slice Start
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqlext.md
Returns the start of the time slice that a given timestamp falls into. Returns NULL if the timestamp is outside the slice. Useful for grouping logs into time buckets.
```custsqlite
;SELECT timeslice('2017-01-01T05:05:00', '10m')
2017-01-01 05:00:00.000000
```
```custsqlite
;SELECT timeslice(log_time_msecs, '5m') AS slice, count(1)
FROM lnav_example_log GROUP BY slice
slice count(1)
2017-02⋯.000000 2
2017-02⋯.000000 1
2017-02⋯.000000 1
```
```custsqlite
;SELECT timeslice(log_time_msecs, 'before 4:30am') AS slice, count(1) FROM lnav_example_log GROUP BY slice
slice count(1)
1
2017-02⋯.000000 3
```
--------------------------------
### Find Substring Occurrence with Start Position
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqlext.md
Searches for the first occurrence of a substring within a larger string, starting from a specified position. Returns the number of characters before the match plus one, or 0 if not found.
```custsqlite
;SELECT charindex('abc', 'abcabc', 2)
4
```
```custsqlite
;SELECT charindex('abc', 'abcdef', 2)
0
```
--------------------------------
### Insert Environment Variable and Use with :open Command
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqltab.md
Insert an environment variable and then use it with the ':open' command for variable substitution. This example inserts 'FILENAME' and opens the specified path.
```custsqlite
;INSERT INTO environ VALUES ('FILENAME', '/path/to/file')
:open $FILENAME
```
--------------------------------
### Define a Custom Theme
Source: https://github.com/tstack/lnav/blob/master/docs/source/config.md
This JSON snippet defines a custom theme named 'example1' for lnav. It sets a custom variable for the background color and applies it to the text style, along with a foreground color. Save this to a file in ~/.lnav/configs/installed/ and activate with ':config /ui/theme example'.
```json
{
"$schema": "https://lnav.org/schemas/config-v1.schema.json",
"ui": {
"theme-defs": {
"example1": {
"vars": {
"black": "#2d2a2e"
},
"styles": {
"text": {
"color": "#f6f6f6",
"background-color": "$black"
}
}
}
}
}
}
```
--------------------------------
### FOOLANG Code Snippet
Source: https://github.com/tstack/lnav/blob/master/test/textfile_0.md
A basic example of FOOLANG syntax.
```foolang
foo bar bar
baz "xyz"
```
--------------------------------
### Basic Configuration File Structure
Source: https://github.com/tstack/lnav/blob/master/docs/source/config.md
A valid lnav configuration file must start with a JSON object containing the '$schema' property.
```json
{
"$schema": "https://lnav.org/schemas/config-v1.schema.json"
}
```
--------------------------------
### Get Base-10 Logarithm
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Calculates the base-10 logarithm of a number.
```sql
;SELECT log10(100)
```
--------------------------------
### Get Natural Logarithm
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Calculates the natural logarithm of a number.
```sql
;SELECT log(8)
```
--------------------------------
### Open Command Prompt with Initial Value
Source: https://github.com/tstack/lnav/blob/master/docs/source/commands.md
Opens the command prompt, pre-filling it with a specified string. Useful for quickly initiating commands like filtering.
```lnav
:prompt command : 'filter-in '
```
--------------------------------
### Highlighting Log Line Patterns with lnav
Source: https://github.com/tstack/lnav/blob/master/test/log-samples/sample-f632067ddac054da85b5cade949c6d94.txt
This example shows how lnav highlights specific patterns within a log line, such as keywords, IP addresses, and message components. It aids in visually identifying relevant parts of the log entry.
```text
key 97:103 ^----^ Sendto
sym 104:108 ^--^ ipv6
val 104:108 ^--^ ipv6
grp 104:108 ^--^
val 104:108 ^--^ ipv6
pair 97:108 ^---------^ Sendto[ipv6
key 110:110 ^
ipv6 110:133 ^--------------------^
val 110:133 ^--------------------^
pair 110:133 ^--------------------^
key 135:135 ^
word 135:137 ^^ No
word 138:143 ^---^ route
word 144:146 ^^ to
word 147:151 ^--^ host
val 135:151 ^--------------^ No route to host
pair 135:151 ^--------------^ No route to host
msg :Sendto[ipv6] fd01:0:106:5:0:a:0:1511: No route to host
format :Sendto[#] #: #
```
--------------------------------
### Get String Length
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Calculates the length of a given string.
```sql
;SELECT length('abc')
```
--------------------------------
### Configure CMake Input Files
Source: https://github.com/tstack/lnav/blob/master/src/CMakeLists.txt
Generates configuration header and markdown files from input templates.
```cmake
configure_file(config.cmake.h.in config.h)
configure_file(help.md.in help.md)
```
--------------------------------
### log_msg_line
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Return the starting line number of the focused log message.
```APIDOC
## log_msg_line()
### Description
Return the starting line number of the focused log message.
### PRQL Name
lnav.view.msg_line
```
--------------------------------
### NOT NULL Check Example
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqlext.md
Checks if an expression evaluates to a non-NULL value.
```custsqlite
;SELECT 'abc' NOT NULL
```
--------------------------------
### Go to Percentage
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Navigates to a specific percentage of the way into the file in the top view.
```lnav
:goto 75%
```
--------------------------------
### fstat(*pattern*)
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqlext.md
A table-valued function for getting information about file paths/globs.
```APIDOC
## fstat(*pattern*)
### Description
A table-valued function for getting information about file paths/globs.
### Parameters
#### Path Parameters
- **pattern** (string) - Required - The file path or glob pattern to query.
### Request Example
```custsqlite
;SELECT ifnull(data, raise_error('cannot read: ' || st_name, error)) FROM fstat('/non-existent')
```
### Response
#### Error Response
- **error** (string)
- **reason** (string)
- **-->** (line number)
### Response Example
```
error: cannot read: non-existent
reason: No such file or directory
--> fstat:1
| SELECT ifnull(data, raise_error('cannot read: ' || st_name, error)) FROM fstat('/non-existent')
```
```
--------------------------------
### Get Base of a Directory
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Returns the base name of a directory path.
```custsqlite
;SELECT basename('foo/bar/')
bar
```
--------------------------------
### Import Regex from Regex101 to Create Format File
Source: https://github.com/tstack/lnav/blob/master/docs/_posts/2022-05-01-regex101-integration.md
Use this command to import a regular expression from regex101.com and create a new skeleton format file. Specify the regex URL, the desired format name, and optionally the regex name within the format.
```console
$ lnav -m regex101 import https://regex101.com/r/zpEnjV/2 re101_example_log
```
--------------------------------
### Show File
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Displays the content of specified files and resumes indexing. Accepts a path or a glob pattern.
```lnav
:show-file path
```
--------------------------------
### Get Base of a Path
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Returns the base name of a given path.
```custsqlite
;SELECT basename('foo/bar')
bar
```
--------------------------------
### Using Environment Variables in SQL Queries
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Demonstrates how to use environment variables within SQL statements by prefixing them with a dollar sign. Variable substitution is performed on fields, not as plain text.
```SQL
SELECT $HOME
```
```SQL
SELECT * FROM syslog_log WHERE log_hostname = $HOSTNAME
```
--------------------------------
### row_number()
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Returns the number of the row within the current partition, starting from 1.
```APIDOC
## row_number()
### Description
Returns the number of the row within the current partition, starting from 1.
### Example
#1 To number messages from a process:
;SELECT row_number() OVER (PARTITION BY ex_procname ORDER BY log_line) AS msg_num,
ex_procname, log_body FROM lnav_example_log
```
--------------------------------
### REGEXP Operator Example
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqlext.md
Checks if a string matches a regular expression pattern.
```custsqlite
;SELECT 'file-23' REGEXP 'file-\d+'
```
--------------------------------
### load_extension(path, [entry-point])
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Loads SQLite extensions out of the given shared library file using the given entry point.
```APIDOC
## load_extension(path, [entry-point])
### Description
Loads SQLite extensions out of the given shared library file using the given entry point.
### Parameters
#### Path Parameters
- **path** (string) - Required - The path to the shared library containing the extension.
- **entry-point** (string) - Optional -
```
--------------------------------
### Open Prompt with Initial Value
Source: https://github.com/tstack/lnav/blob/master/src/internals/cmd-ref.rst
Opens a prompt with a specified type and an initial value. The 'command' type opens the command prompt, and 'user' opens a confirmation prompt.
```lnav
:prompt command : 'filter-in '
```
```lnav
:prompt user 'Are you sure? '
```
--------------------------------
### Get Sign of a Number
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Returns the sign of a number (-1, 0, or 1).
```custsqlite
;SELECT sign(10)
1
```
```custsqlite
;SELECT sign(0)
0
```
```custsqlite
;SELECT sign(-10)
-1
```
--------------------------------
### Create Partitions for Linux Boots
Source: https://github.com/tstack/lnav/blob/master/docs/source/cookbook.md
Use a custom SQLite script to partition log messages based on Linux kernel boot messages, creating distinct sections for each boot.
```custsqlite
#
# DO NOT EDIT THIS FILE, IT WILL BE OVERWRITTEN!
#
# @synopsis: partition-by-boot
# @description: Partition the log view based on boot messages from the Linux kernel.
#
;UPDATE syslog_log
SET log_part = 'Boot: ' || log_time
WHERE log_text LIKE '%kernel:%Linux version%';
;SELECT 'Created ' || changes() || ' partitions(s)';
```
--------------------------------
### Get Base of a Windows Path
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Returns the base name of a Windows-style path.
```custsqlite
;SELECT basename('foo\bar')
bar
```
--------------------------------
### lnav Journald URL Handler Example
Source: https://github.com/tstack/lnav/blob/master/NEWS.md
Demonstrates how to use the 'journald://' URL handler to query journalctl logs with specific parameters.
```shell
$ lnav 'journal://?since=yesterday'
```
--------------------------------
### Get Base of an Empty String
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Returns the base name of an empty string.
```custsqlite
;SELECT basename('')
.
```
--------------------------------
### Execute Plain SQL File
Source: https://github.com/tstack/lnav/blob/master/NEWS.md
Execute SQL commands from a plain SQL file using the ";.read" command.
```sql
;.read /path/to/sql/file.sql
```
--------------------------------
### Get the Value of PI
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
The pi() function returns the mathematical constant PI.
```SQL
;SELECT pi()
```
--------------------------------
### Find Substring Not Found
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Demonstrates searching for a substring that is not present from the specified start position.
```custsqlite
;SELECT charindex('abc', 'abcdef', 2)
0
```
--------------------------------
### Project Configuration
Source: https://github.com/tstack/lnav/blob/master/CMakeLists.txt
Sets the minimum required CMake version and defines the project name, version, description, and supported languages.
```cmake
cmake_minimum_required(VERSION 3.14)
include(cmake/prelude.cmake)
set(CMAKE_CXX_STANDARD 17)
project(
lnav
VERSION 0.14.1
DESCRIPTION "An advanced log file viewer for the terminal."
HOMEPAGE_URL "https://lnav.org/"
LANGUAGES CXX C
)
```
--------------------------------
### Python Function Example
Source: https://github.com/tstack/lnav/blob/master/test/textfile_0.md
A Python function that prints a greeting, including a docstring and a comment.
```python
def hw(name):
"""
This function prints "Hello, !"
"""
print(f"Hello, {name}!") # test comment
```
--------------------------------
### Create LNAV Data Library
Source: https://github.com/tstack/lnav/blob/master/src/CMakeLists.txt
Builds a static library 'lnavdt' including configuration headers, time format sources, and third-party date library headers.
```cmake
add_library(lnavdt STATIC config.h.in ptimec.hh ptimec_spec.hh ptimec_rt.cc time_fmts.cc)
target_include_directories(lnavdt PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
third-party/date/include)
```
--------------------------------
### Get Base of the Root Directory
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Returns the base name of the root directory path.
```custsqlite
;SELECT basename('/')
/
```
--------------------------------
### Example Log Format Configuration
Source: https://github.com/tstack/lnav/blob/master/docs/source/formats.md
This JSON object defines a sample log format for lnav, including regex for parsing, level mapping, and sample log lines.
```json
{
"$schema": "https://lnav.org/schemas/format-v1.schema.json",
"example_log" : {
"title" : "Example Log Format",
"description" : "Log format used in the documentation example.",
"url" : "http://example.com/log-format.html",
"regex" : {
"basic" : {
"pattern" : "^(?\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z)>>(?\\w+)>>(?\\w+)>>(?.*)$"
}
},
"level-field" : "level",
"level" : {
"error" : "ERROR",
"warning" : "WARNING"
},
"value" : {
"component" : {
"kind" : "string",
"identifier" : true
}
},
"sample" : [
{
"line" : "2011-04-01T15:14:34.203Z>>ERROR>>core>>Shit's on fire yo!"
}
]
}
}
```
--------------------------------
### Get String Length
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Use the length function to find the number of characters in a string.
```sql
;SELECT length(str)
```
--------------------------------
### Create a New App using Management CLI
Source: https://github.com/tstack/lnav/blob/master/docs/source/extacc.md
Creates a new app for lnav's external access feature using the management CLI. This command generates a configuration directory and a sample index.md file.
```bash
lnav -m apps create mydash
```
--------------------------------
### startswith(str, prefix)
Source: https://github.com/tstack/lnav/blob/master/test/expected_help.txt
Test if a string begins with the given prefix.
```APIDOC
## startswith(str, prefix)
### Description
Test if a string begins with the given prefix.
### Parameters
#### Path Parameters
- **str** (string) - The string to test
- **prefix** (string) - The prefix to check in the string
### Request Example
```sql
SELECT startswith('foobar', 'foo')
```
### Request Example
```sql
SELECT startswith('foobar', 'bar')
```
```
--------------------------------
### Highlight Java Package Names
Source: https://github.com/tstack/lnav/blob/master/docs/source/formats.md
Example JSON configuration for highlighting Java package names within a 'tag' field. It defines a base style for the package and a specific style for the class name.
```json
"tag": {
"kind": "string",
"identifier": true,
"highlights": {
"package": {
"pattern": "(?([a-z]+\\.){2,})(?[a-z]+)(?=[ '\"])",
"base-style": {
"color": "#97d1F6"
},
"captures": {
"cls": {
"color": "#c0d1F6",
"bold": true
}
}
}
}
}
```
--------------------------------
### Extract Directory from Windows Path
Source: https://github.com/tstack/lnav/blob/master/docs/source/sqlext.md
Use `dirname` to get the directory portion of a Windows-style path.
```custsqlite
;SELECT dirname('foo\bar')
```
--------------------------------
### Get Root JSON Value
Source: https://github.com/tstack/lnav/blob/master/src/internals/sql-ref.rst
Retrieves the entire JSON object when an empty JSON-Pointer is provided.
```custsqlite
;SELECT jget('1', '')
1
```
--------------------------------
### Initialize Generated Source List
Source: https://github.com/tstack/lnav/blob/master/src/CMakeLists.txt
Initializes an empty list to store generated source files.
```cmake
set(GEN_SRCS "")
```